(key, initialValue)
| 1 | import { useState } from "react"; |
| 2 | |
| 3 | export default function useLocalStorage(key, initialValue) { |
| 4 | // Pass initial state function to useState so logic is only executed once |
| 5 | const [storedValue, setStoredValue] = useState(() => { |
| 6 | try { |
| 7 | const item = window.localStorage.getItem(key); |
| 8 | return item ? JSON.parse(item) : initialValue; |
| 9 | } catch (error) { |
| 10 | console.log(error); |
| 11 | return initialValue; |
| 12 | } |
| 13 | }); |
| 14 | |
| 15 | // Return a wrapped version of useState's setter function that |
| 16 | // persists the new value to localStorage. |
| 17 | const setValue = (value) => { |
| 18 | try { |
| 19 | // Allow value to be a function so we have same API as useState |
| 20 | const valToStore = value instanceof Function ? value(storedValue) : value; |
| 21 | setStoredValue(valToStore); |
| 22 | window.localStorage.setItem(key, JSON.stringify(valToStore)); |
| 23 | } catch (error) { |
| 24 | console.log(error); |
| 25 | } |
| 26 | }; |
| 27 | |
| 28 | return [storedValue, setValue]; |
| 29 | } |
nothing calls this directly
no outgoing calls
no test coverage detected