Atomic State Management in React
Before we get started, let’s answer the next question.
Where does the state live?
Well, it depends. React developers usually use two approaches to organize application state, component state (useState) and global store (Redux). Accordingly, the state can live in relation with component or in Redux store, to be short, it is tightly coupled with the originator and cannot be created independently.
It solidly limits the software designer to organize the software architecture with desired patterns.
Have you ever wanted to use useState
hook, but pass a reference to your state object?
Atoms
Atomic State Management implies using Atoms as a single source of the state. It’s like useState
that can be shared between components. It took advantages from both component state and global store patterns into one approach.
It’s short in writing and easy to share between components, as demonstrated in the example below.
// product.state.js
const priceAtom = createAtom(15);
const discountAtom = createAtom(10);
const discountedPriceAtom = createAtom((get) => get(priceAtom) / 100 * get(discountAtom));
// product.component.js
const Header = () => {
const [price, setPrice] = useAtom(priceAtom);
const [discountedPriceAtom] = useAtom(discountedPriceAtom);
...
}
As you can see there is no need to have a huge boilerplate code to have a globally accessible state. You are free to define the state wherever you want, global level, near the component or module level, it depends on your architecture and taste.
Libraries
There are two most popular libraries that implement atomic state management patterns, Recoil (coordinated by Facebook) and Jotai, and they already have implemented selectors, async setters, devtools integrations, time-traveling, etc.
TL;DR Use atomic state management techniques to achieve better flexibility in organizing application state management.
Hope this will be helpful for you and your team and will let you focus on important things!