DEV Community

loading...

What is the best option for dead simple state management with React?

nicfitzgerald profile image Nic FitzGerald (they/them) ・1 min read

I am creating a blog front-end for my client. I, previously, was fetching data for the front-end on every component that required it... however I decided that was probably not the best idea. I am looking for a central "state", if you will, that I can fetch all the required data and have it available to whatever component will need it. There will be no mutating of the data (beyond sorting and the like), and there will be no updating the data, beyond whenever a call is made to the API in general. What would my best options be? I found this link that seems like it would work, but I didn't know if something like that already exists.

Any and all help/ideas are appreciated.

Thank you.

Discussion (5)

pic
Editor guide
Collapse
veevidify profile image
V • Edited

Sounds like redux and thunk fits your use case. Thunk helps you organize your asynchronous API calls (dispatch actions to reducer after a Promise resolve your backend response).

The downsides (from my experience) so far are:

  • Setting up action/ reducer/ middleware takes a bit of work (once you're set up, writing actions and reducers become very simple).
  • You have to be careful about being too eager when mapping central state to components, especially when it is a large array; reducer's immutable pattern creates new array most of the time. From a glance, the article mentioned it and they used shouldComponentUpdate to block unnecessary re-render, and their use case is basic & clean. Ideally you want to avoid interfering with React component lifecycle with complicated logic, but if you need to do it, you gotta be very careful when creating conditions for it, otherwise you could end up with redux state and component rendered view out-of-sync all over the places.
Collapse
dylanesque profile image
Michael Caveney

This right here, if you need a central store that oversees state, that is literally one of the most useful features that Redux provides. There's definitely a learning curve, but it can really pay off in dividends once you get used to it.

Collapse
spacemonkey profile image
Mitch Pirtle

I've been playing with MobX which makes this much simpler, and they also provide pitfalls and FAQs. Generally the documentation is pretty good.

Most relevant to your case is the use of Stores which might be a good fit for your use case.

Collapse
dylanesque profile image
Michael Caveney

Which state-management solutions have you considered so far, apart from the link in the article?

Collapse
nicfitzgerald profile image
Nic FitzGerald (they/them) Author

I've used Redux and taken the briefest of glimpses into Mobx as well as... I can't recall the name atm, the built in React system. I have a link pulled up on a different machine.