Search code examples
reactjsstate

Difference between computed state and regular state?


I was told that I have been using too many states in my react project and that I should use computed state instead of using regular state but I am unable to understand what computed state really is, how to use it and when it is appropriate to use it and how it differs from regular state?

I have tried looking up resources on google but I still could not really grasp it. Any guidance or examples would be greatly appreciated.


Solution

  • Computed state refers to values that are derived from state or props. Computed state is reactive, exactly like normal state.

    The advantage of a computed state is that you dont need to manually manage your derived state, react takes care of that for you.

    I ripped this example from the react docs to show an example of it.

      const [firstName, setFirstName] = useState('Taylor');
      const [lastName, setLastName] = useState('Swift');
      // ✅ Good: calculated during rendering
      const fullName = firstName + ' ' + lastName;
      // ...
    }