Skip to content

Instantly share code, notes, and snippets.

@MaymoonaAlBoloshi
Created June 19, 2022 08:32
Show Gist options
  • Save MaymoonaAlBoloshi/04df72cddd491c93c0c678caf2c6b5a4 to your computer and use it in GitHub Desktop.
Save MaymoonaAlBoloshi/04df72cddd491c93c0c678caf2c6b5a4 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
export const usePersist = (key: string, initialValue: any) => {
const [value, setValue] = useState(() => {
const storedValue = localStorage.getItem(key);
return storedValue ? JSON.parse(storedValue) : initialValue;
}
);
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}
, [value]);
return [value, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment