How does Recoil's atom based approach to state differ from Redux's single central store?
Short answer
Recoil breaks shared state into small, independent pieces called atoms, and each component subscribes only to the specific atoms it actually needs, rather than the entire store like Redux.
Advertisement
AModel answer
Recoil breaks shared state into small, independent pieces called atoms, and each component subscribes only to the specific atoms it actually needs, rather than the entire store like Redux. This can reduce unnecessary re renders, since changing one atom does not affect components that only depend on a completely different atom.
import { atom, useRecoilState } from 'recoil';
const cartCountState = atom({ key: 'cartCount', default: 0 });
function CartBadge() {
const [count] = useRecoilState(cartCountState);
return <span>{count}</span>;
}Real-world example
A dashboard app uses separate Recoil atoms for the sidebar's collapsed state and the currently selected report, ensuring that updating one does not cause components relying on the other to re render unnecessarily.
Likely follow-ups
- How does Recoil's approach compare in terms of learning curve to Zustand's simpler model?
- What does an atom's key actually need to be unique across?
Related topics