Created
June 19, 2022 08:32
-
-
Save MaymoonaAlBoloshi/04df72cddd491c93c0c678caf2c6b5a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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