React: different types of state management

This is my classification of different types of state management in React.

 

1. React context

This is a native mechanism in react core.
Actually context is not exactly state management tool, it is kind of Dependency Injection. Context provides a way to pass data through the component tree without having to pass props down manually at every level. It is best used when you have some value that is rarely changed and you want to make it accessible to a portion of your React component tree (without passing that value down as props through each level of components).

Issues:

  • Making a change in some inner param of the state object that is stored in a context will rerender all the consumers of this context (even if they don't use this specific param). So context can only store a single value, not an indefinite set of values each with its own consumers.
  • Context hell - using this approach as a state management tool will lead us to many nested contexts in different places in react tree.

 

2. Global store

Notes:

  • redux: One of the most known state management solutions in JS world. Lots of boilerplate - actions, reducers, selectors.
  • zustand: A small, fast and scalable state-management solution using simplified flux principles. It requires much less boilerplate code due to its opinionated approach. In zustand the store doesn't have to be global, but still..
  • Complicated store mutation. Need to create immutable path when modifying some nested state. Using utils like immer or immutable may help to manipulate the store.

 

3. Magic store

Notes:

  • Need to be aware of the fact that it is proxy and of the specific rules of this kind of state management.

 

4. Atomic model

Notes:

  • A boilerplate-free API where shared state has the same simple get/set interface as React local state (useState/useAtom).
  • recoil is not production ready yet (11/2021).

 

Network request global cache

These libraries help to perform network requests in React. One of the main features of these libraries is to keep the requests in cache. So next time you perform the same request, you will get a cached response. It doesn't metter where in the react tree you perform this request, the cache is global and behaves like a global state management solution for network requests.

 

5. REST cache

Notes:

  • SWR (stale-while-revalidate) is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

 

6. GraphQL cache

Notes:

  • Apollo uses normalized cache which reduces data redundancy but is more complicated.

P.S. In my latest project I chose jotai, react-query and apollo.
:)

16