You SHOULD derive your state in React

Topic is not new but the more I work this concept is forgotten and rediscovered all over again. Your component can be small and swift, but it becomes doing more and more. Apply now this easy rules and thanks me later.
What is deriving state?
Deriving state is computing value based on the data we already have. This means figuring out a value based on props or state we already have.

Good, deriving value from data
How that differs from setting state?
When you're setting state you manage multiple source of data. This involves syncing the value and state between each other. You doing ping-pong game to reflect user changes into data and data into interface.

Bad, setting value independently
How to derive state in React?
Let’s see how state is usually set and how we can avoid such situation in React.
Sample setting state react code:
// ❌ Bad! Setting state
function Component(props) {
const [values, setValues] = useState(null);
const [isOptionalSet, setIsOptionalSet] = useState(null);
useEffect(() => {
if (!!values.optional) {
setIsOptionalSet(true);
} else {
setIsOptionalSet(false);
}
}, [values, setIsOptionalSet]);
return (
<div>
<FormComponent onSubmit={(values) => setValues(values)} />
{isOptionalSet && (
<OptionalFormComponent />
)}
</div>
)
}
This example can be trivial, but I saw similar examples in codebases I worked on. Example code is checking form values when optional value is present, or not. Then, setting flag to show optional form component. Seems like straightforward code, but beware, it will re-render every time values change.
Above code can be refactored to derive state from values instead of setting new state.
// ✅ Good! Deriving state from values
function Component(props) {
const [values, setValues] = useState(null);
const isOptionalSet = !!values?.optional;
return (
<div>
<FormComponent onSubmit={(values) => setValues(values)} />
{isOptionalSet && (
<OptionalFormComponent />
)}
</div>
)
}
Much better, simpler without additional re-render when values change. This code derive isOptionalSet from values in rendering phase. Meaning is always up-to-date with values. No need for useEffect to sync state!
Summary
Deriving simplify your code. It’s faster, easier and less error-prone. You should use deriving technique always when possible.