Local State Vs Global State
There are two kinds of state in React
- Local State - Accomplished with React State
- Global State - Usually required third party libraries
Local States
- When states are only required within a component, and not outside that component, we should utilize local states.
- E.g. form input values and respective validation states such as error states for the form inputs are only required within that form component. Hence these states should be maintained locally
Global State
- When states are shared between two or more components. And these components might be anywhere in the UI tree, deeply nested, then use global state.
- E.g. When some information is derived from expensive computation or network call in Page A, and the same data can be used in Page B, we can store the computed data in a global state.
- Need a third party library such as redux (most popular), zustand, xState, jotai, signals etc.
danger
Don't store form input states on global state directly, it'll be updated on every input change. It can cause huge performance problems. Instead handle all the input changes with local state using React.useState()
and only store the final value to redux.
info
React context seems like global state management solution, but it's not. And NO we cannot implement global state management solution using Context with reducers. Read ahead 👉🏽