Skip to content

Instantly share code, notes, and snippets.

@icarus-sullivan
Last active July 5, 2019 20:37
Show Gist options
  • Save icarus-sullivan/f9cab46ee8270df0ffd76f5425a803ca to your computer and use it in GitHub Desktop.
Save icarus-sullivan/f9cab46ee8270df0ffd76f5425a803ca to your computer and use it in GitHub Desktop.
Declaring an external hook, that we can pull into our components
import { useCallback, useState } from 'react';
export const usePersistState = ({ key, defaultValue }) => {
const [value, setValue] = useState(JSON.parse(localStorage.getItem(key) || JSON.stringify(defaultValue)));
const setter = useCallback((value) => {
localStorage.setItem(key, JSON.stringify(value));
setValue(value);
});
return [value, setter];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment