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";
function MyComponent() {
const [value, setValue] = usePersistedState("my-component-value", "");
return (
<input
type="text"
placeholder="Type things..."
value={value}
onChange={event => setValue(event.target.value)}
/>
);
}