Search code examples
reactjs

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


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?


Solution

  • 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:

    1. If you design your components tree in clean way, no need to use getDerivedStateFromProps. Usually it is not good practice to have another state from prop. getDerivedStateFromProps can be useful for heavy calculation to get state from props but it should be avoided in general. For instance, we can pass down the already calculated prop from parent to children. So.. in clean structure/code, we don't need to use getDerivedStateFromProps which increases complexity.

    2. Calculation on the fly can be more performant in most of cases. e.g: const numberOfItems = items.length + 1; is much faster than using getDerivedStateFromProps to avoid that calculation.