Skip to content

Instantly share code, notes, and snippets.

@mcnaveen
Created January 29, 2022 15:54
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 mcnaveen/52b130146b5be057151d9ff95c138d59 to your computer and use it in GitHub Desktop.
Save mcnaveen/52b130146b5be057151d9ff95c138d59 to your computer and use it in GitHub Desktop.
Persist state after a page refresh in React
const storedValueAsNumber = Number(localStorage.getItem("limit"));
const [userLimit, setUserLimit] = useState(
Number.isInteger(storedValueAsNumber) ? storedValueAsNumber : 0
);
useEffect(() => {
localStorage.setItem("limit", String(userLimit));
}, [userLimit]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment