DEV Community


Discussion on: Next.js persistent state with React hooks and localStorage. How to make it work?

nvio profile image
Steven Yung • Edited

Hello Klaudiusz!

I found your thread on Google trying to solve mine 😂

I don't have a similar issue but I successfully did something similar, I figure, it's better that I post it than not at all.

export const PostsContextProvider = ({ children, storageKey = "posts" }) => {
  const [isInitialized, setIsInitialized] = useState(false);

  const [posts, dispatchPost] = useReducer(reducer, []);

  useEffect(() => {
    if (isInitialized) {
      localStorage.setItem(storageKey, JSON.stringify(posts));
  }, [posts]);

  useEffect(() => {
        type: SET_POSTS,
        value: JSON.parse(localStorage.getItem(storageKey)) || []

  }, []);

  return (
    <PostsContext.Provider value={{ posts, dispatchPost }}>
Enter fullscreen mode Exit fullscreen mode

As you can see, my version use 2 useEffect. One to initialized the data using the localStorage if it's there is something (otherwise, it defaults to []) and one to keep the localStorage updated with the app.

Happy to answer question if you have some 👍