Skip to content

Instantly share code, notes, and snippets.

@andreadev-it
Last active July 18, 2023 15:42
Show Gist options
  • Save andreadev-it/f2d59e3e76e08208ea912b4fded3f2f5 to your computer and use it in GitHub Desktop.
Save andreadev-it/f2d59e3e76e08208ea912b4fded3f2f5 to your computer and use it in GitHub Desktop.
Little react hook to create a state varaiable that is also preserved in localstorage any time it changes
/*
* To see an example on how to use this hook, check out this codePen: https://codepen.io/andreadev-it/pen/NWgaWwz
*/
import { useState, useEffect } from 'react';
/*
* Implementation of the useLocalStorage hook
*
* @param {any} init The initial value of the variable to be saved. It will only be used if the variable isn't found in localstorage.
* @param {string} label The key that will be used to refer to this variable inside localStorage.
*/
export function useLocalStorage(init, label) {
let stored = JSON.parse(localStorage.getItem(label));
const [data, setData] = useState(stored || init);
useEffect(() => {
if (data == null)
localStorage.removeItem(label);
else
localStorage.setItem(label, JSON.stringify(data));
}, [data, label]);
return [data, setData];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment