Skip to content

Instantly share code, notes, and snippets.

@nyg
Created December 29, 2023 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyg/d81aaeaaa207d37b144f5fcc02e7b94d to your computer and use it in GitHub Desktop.
Save nyg/d81aaeaaa207d37b144f5fcc02e7b94d to your computer and use it in GitHub Desktop.
Custom useLocalStorage hook for Next.js
// Based on https://usehooks.com/useLocalStorage/, modified to be used with
// Next.js' server-side rendering components.
import { useState } from "react";
export default function useLocalStorage(key, initialValue) {
// There is no need to pass the inital value here as this will be executed on
// the server side, so window.localStorage is not available.
const [stateValue, setStateValue] = useState()
// Wraps useState's setter function, and persists the new value to
// localStorage when executed.
const setValue = newValue => {
setStateValue(newValue)
window.localStorage.setItem(key, JSON.stringify(newValue));
}
// Define an init function to be used in useEffect so that's it's executed on
// the client-side where localStorage is available.
// If the localStorage value is null then it is initialized, if it's not then
// the state is updated with this value.
//
// useEffect must be used with empty dependencies, i.e. useEffect(…, [])
const initValue = () => {
const currentValue = window.localStorage.getItem(key)
if (currentValue === null) {
window.localStorage.setItem(key, initialValue)
}
else {
setStateValue(currentValue)
}
}
return [stateValue, setValue, initValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment