Skip to content

Instantly share code, notes, and snippets.

@Ah-ae
Created March 5, 2023 14:29
Show Gist options
  • Save Ah-ae/c980cdb576a5ba7acc956db3a9b9be54 to your computer and use it in GitHub Desktop.
Save Ah-ae/c980cdb576a5ba7acc956db3a9b9be54 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialState) {
const [state, setState] = useState(
() => JSON.parse(window.localStorage.getItem(key)) || initialState
);
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
return [state, setState];
}
export default useLocalStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment