DEV Community

Discussion on: Persisting your React state in 9 lines

Collapse
 
mxmzb profile image
Maxim • Edited

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-blown react-redux + redux-persist setup.

Collapse
 
fredericocotrim profile image
fredericocotrim

Could you share your approuch using usePersistedState on useReducer?

Collapse
 
jcaguirre89 profile image
Cristobal Aguirre • Edited

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:

const initialState = {
  //other state
  cartItems: JSON.parse(localStorage.getItem('cart_items')) || [],
}

function reducer(state, action) {
  switch (action.type) {
    case 'UPDATE_CART': {
      const { variantId, quantity } = action.payload;
      const updatedCartItems = state.cartItems.filter(
        i => i.variantId !== variantId
      );
      const cartItems = [...updatedCartItems, { variantId, quantity }];
      // write to localStorage <-- key part
      if (typeof window !== 'undefined') {
        localStorage.setItem('cart_items', JSON.stringify(cartItems));
      }
      return {
        ...state,
        cartItems,
      };
    }

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!

Collapse
 
islami00 profile image
islami00

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.