Here is the code for a hook that wraps the useState
hook and persistes the value in a cookie. There are lots of other implementations of a similar hook (e.g. https://dev.to/selbekk/persisting-your-react-state-in-9-lines-of-code-9go) but they don't work with Next.js because localstorage
is not available on the server.
import React from "react";
import usePersistedState from "./usePersistedState";