back to notes

State Management

March 16, 2025

State Management refers to a cleaner way to store the state variables. State variables are usually separated from the components. It solves the problems of Context API that is unnecessary re-renders

Recoil

A state management library for react

Atom

Atoms are units of state. They're updatable and subscribable. when an atom us updates, each subscribed component is re-rendered with the new value. If the same atom is used from multiple components, all those components share their state.

Smallest unit of state. An atom is used to store the state. It is defined outside the component. Can be used in any component

RecoilRoot

All the components that used recoil must be wrapped inside the <RecoilRoot>

useRecoilState

Similar to the useState that gives access to both the value and setValue variables. Used in the component where you want to display as well as update the state variable.

useRecoilValue

Gives access to only the value of the state variable. Used in components that do not have any update logic, they are used only to display the state variable.

useSetRecoilState

Gives access to the setValue function. Used in components that handle the update logic of the state variables.

selector

Selectors are used to calculate derived data that is based on state.

The get property is the function that is to be computed. It can access the value of atoms and other selectors using the get argument passed to it. Whenever it accesses another atom or selector, a dependency relationship is created such that updating the other atom or selector will cause this one to be recomputed.

(Similar to useMemo)