Date: February 19, 2025
The derived state describes a state calculated from an existing state or props rather than being kept separately.
Key Idea: Instead of creating multiple pieces of state, compute values from existing state to avoid unnecessary updates and re-renders.
๐จ Problems with Redundant State
If we create unnecessary state variables:
State Synchronization Issues
When multiple states depend on each other, they must be updated to stay in sync.
The UI may show incorrect data if one state is updated and another isn't.
Unnecessary Re-renders
Each `useState` update triggers a separate re-render.
If multiple dependent state variables are updated separately, React will re-render the component multiple times, causing performance issues.
Keeps state in sync automatically
Reduces the number of re-renders
Improves code simplicity and maintainability
๐น Use derived state when:
The value can be calculated from the existing state or props.
You want to avoid unnecessary re-renders.
You need to keep dependent state values in sync
๐น Do NOT use derived state when:
The value requires user interaction to change.
The value cannot be calculated from existing data.
The computation is expensive (complex calculations, API calls, etc.) โ Use `useMemo`.
โ Avoid storing unnecessary stateโonly store data that cannot be computed.
โ Use derived state whenever a value depends on existing state or props.
โ Use `useMemo` for optimizing expensive calculations.