The other day I was browsing LinkedIn when a poll caught my eye
What's your favourite React State Management Library and why?
Naturally, I felt there was an option missing from the poll and left a comment. I replied saying I felt a custom hook with the context API should be enough, let's talk about that.
Before we look at what state management is we have to agree on what state is. State is a place in memory where we can store some data, anything really. For instance with a checkbox it is either checked or not, true or false, and they are its states, storing a user's name as a string is a state or an array of preferences, the list is endless.
So what is state management? These states/variables need to be interacted with some how. Be it reading the value or setting it. In it's most simple form state management is how you interact with a variable.
In React, states are easy provided you only want to touch them inside the components they were made in. State Management Library's, for React, make it possible to interact with states from anywhere without having to prop drill. This is great and it why these libraries are so popular but is there a better way?
The context API is a default React hook used to allow data (objects, functions, strings, etc) to be accessed by any child component.
When we use this API in tandem with a custom hook it gets a lot more powerful. We can pass objects with
setter functions that can be used read or modify states, as you'd expect, or have functions that allow us to set several states at once or even give us data back in certain formats, perhaps for API calls.
Here I've written a very simple hook to manage storing a person's name. It stores a first and last name, which you can both get and set, it also concatenates the two names into one long name that can be read from context, this is not something you'd ever really need to do but it shows how data can be returned formatted, there is also a function that lets you set both states at once.
Have a look through the code, as I said it's nothing complex but it was only meant to serve as an example of what can be done rather than a template to be followed.
With all of this power built into React do we need State Management Libraries? Maybe we do or maybe we don't but either way please let me know if you use one and if you do why? I look forward to reading your comments.
Thank you so much for reading.