Skip to content

Instantly share code, notes, and snippets.

@jkimbo
Last active February 3, 2020 17:16
Show Gist options
  • Save jkimbo/17ab35e9fd330edf4dc217ecd678b695 to your computer and use it in GitHub Desktop.
Save jkimbo/17ab35e9fd330edf4dc217ecd678b695 to your computer and use it in GitHub Desktop.

usePersistedState hook for Next.js

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.

Usage

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)}
    />
  );
}
import React from "react";
import nextCookie from "next-cookies";
import { PersistedStateContext } from "./usePersistedState";
export default App({ Component, pageProps, persistentState }) {
return (
<PersistedStateContext.Provider value={persistentState}>
<Component {...pageProps} />
</PersistedStateContext.Provider>
);
}
App.getInitialProps = async ({ Component, ctx }) => {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
const cookies = nextCookie(ctx);
return {
persistentState: cookies["persisted_state"] || {},
pageProps,
};
};
import React, { useState, useEffect, useContext } from "react";
export const PersistedStateContext = React.createContext({});
export default function usePersistedState(key, initialValue) {
const values = useContext(PersistedStateContext);
const [state, setState] = useState(() =>
values && values[key] !== undefined ? values[key] : initialValue,
);
useEffect(() => {
if (state !== values[key]) {
const cookies = new Cookies();
cookies.set("persisted_state", {
...values,
[key]: state,
});
}
}, [key, state, values]);
return [state, setState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment