What is derived state in React, and why is it important?

Viewed 8230

There are many answers online explaining why we probably don't need derived state, but what is it exactly? Where is it being "derived from"? Why does it matter, and how is it different from the correct way of handling state in a react app?

1 Answers

Update July 2nd 2022 - In React Hook

We can use useMemo to have cache based reactive state.

e.g:

const firstName = useState('John');
const lastName = useState('Doe');

// fullName will be re-calculated only when firstName or lastName changes
const fullName = useMemo(() => `${firstName} ${lastName}`, [firstName, lastName]);


Derived state is a state which mainly depends on props.

static getDerivedStateFromProps(props, state) {
  if (props.value !== state.controlledValue) {
    return {
      controlledValue: props.value + 1,
    };
  }
  return null;
}

In the above codes, controlledValue is a derived state which depends on value prop.

Then why we avoid to use these derived states?

The answer is simple: To reduce needless re-rendering.

In details, as we know, when any prop or state is changed then it will make the component to re-render. Then let's assume that value props is changed in the above codes, then it will try to re-render the component and also controlledValue state is also updated. That will also try to re-render.

So in fact, for only one update for a prop, but two re-renders.

Example:

render() {
  return (
    <div>
      <span>{this.state.controlledValue}</span> // same as this.props.value + 1
    </div>
  );
}

The two lines of output will be same, but when the prop is changed the component should be re-rendered twice.

But If we calculate output value from prop then, We don't need this controlledValue state. Then the component will be re-rendered only once.

Related