Most of the time you don’t have big application state management in the client, but a copy of your server data that you got in fetch request.
- For “server cache”: using GraphQL? you might want to use Apollo Client use react-query library or zeit’s swr
- For component state - use
useState(simple data) or
useReducer(complex data) hooks.
- For small application state (like showing notifications) - use
- For large application state - use state management library like redux.
What is local state management
When you think about local state management the first world in your head might be redux. Redux is a very popular tool this days, and it ecosystem improves over and over (see redux toolkit). For me when I think about redux I think more about the Flux architecture it’s more like a pattern. Instead of creating a lot of local states that sits inside the components, you have one global store that represent the “single source of true” for your app.
So your components won’t replicate the same state over and over, and the data will be consistent all over your app. You modify this data you need to
dispatch actions and then your reducer will replace the global state. After the state changes your connected views will update accordingly (react-redux make the state in the context of your app)
So why not using redux as always
Redux has a lot of boilerplate that you don’t need. There are some libraries that are build on the top of redux like rematch that help us handle it in less boilerplate and higher level. But compared to the “cache” solution of graphql or react-query does a lot of work. Also, there is a good blog post of Mark Erikson that says that redux is not dead, but you might not need it as Dan Abramov wrote.
If you have automatic tool that handle the state management of server request, it’s better to use it instead of writing it manually
What is react-query
If you use graphql with apollo so you might notice that Apollo is trying to use it’s cache wherever possible (actually it has cache policies for that). So if I ask for some field and I already fetched it, apollo will not make an https request. It resolve the value from the cache. Also, I can get the fresh data if I want by simply change one param. react-query do the same for REST API.
Subscribe to Nir Tamir
Get the latest posts delivered right to your inbox