I was playing around with a project from Frontend Mentor this weekend, and I was implementing this theme switcher with React hooks. It struck me th...
For further actions, you may consider blocking this person and/or reporting abuse
Really nice, thank you Kristofer! This is a very pragmatic approach. I kind of like Redux, and you inspired me to add a construct
React.useReducer
on top of this. It might be just the perfect substitute for a full-blownreact-redux
+redux-persist
setup.Ikr! I was also considering learning redux to persist the state left over from react query.
The main thing I was running away from was typing reducers because I use typescript. I think I'll try this with a custom json serialise function for any special objects by prepping them as classes. I'll update the design I had in mind initially with useReducer.
(Taking notes here now, haha) The reducer is a bit like redux in the sense that there's one global reducer that has a root and nodes of different ui components in the state tree. It would be generic enough to have typings and allow other components to have their own custom branch of this node.
I guess the localstate update would need to be more complex in that case to avoid chucking it all in one key. Hmm, I wonder what the limit for that is really.
Could you share your approuch using usePersistedState on useReducer?
I adapted both this post and this blog post by Swizec Teller to get what I wanted using useReducer. I'm making an ecommerce site and wanted to persist the cart items. So I did:
and then plugged that into context. If you need more context, I'm using gatsby and followed this guide to set up the state mgt. logic.
Hope it helps!
In case you're storing falsy values, you might want to initialize the state like this:
Hey, can I use this code in a class-based component? Or can it only be used in a functional component whose state is managed with Hooks?
Hi! Hooks unfortunately require function components to work, but you could recreate the same functionality with either a HOC or just directly in your class component. In your
componentDidUpdate
, add a line that serializes and saves your state to local storage.When you initialize the state, you need to do the reverse:
Hope that helps!
Hi @selbekk , thanks so much for your post and this comment reply. When I tried to implement this class-based version, I encountered the following (unfamiliar) error:
Error: Objects are not valid as a React child (found: object with keys {type, key, ref, props, _owner, _store}). If you meant to render a collection of children, use an array instead.
I'm trying to track down this error, but do you have any suggestions to point me in the right direction?
That happens when you try to render a regular object as children. Iβd have to see more of the related code to be of any assistance
Thanks @selbekk , for your reply. That was indeed the case - I was implementing the class-based version in the wrong place within the component hierarchy. The quick fix was simply to locally store only the single piece of state that needed to persist, rather than the entire state object. Works like a charm, and I'm grateful for this post.
Probably need to JSON.stringify that object to store the data in local storage.
Hi @selbekk , nice article! Can you explain a little about the last section(about optimization)? How would
() => JSON.parse(localStorage.getItem(key))
inside useState() work? Wouldn't it not work, since it is declared, not invoked inside useState()?
Thanks!
When you pass a function as an argument to useState instead of a "regular" value, it is only run on the initial render. Itβs a way React offers to do initialization work only once, instead of on each render.
What if an Async Storage solution is being used, like AsyncStorage on react native?
This is awesome!
Thanks for this! Can you explain how we would actually use this within the application?
Hi Stephanie!
You would copy the source code into your project, and import the usePersistentState hook where you would want to use it
This was very helpful βΊοΈ thanks for sharing π
Great custom hook, I already used it in several projects. Are you gonna make it an NPM package?
For 9 lines of code? Iβd rather just copy it. But feel free to make a package out of it yourself if you want to π₯³