Lesson 12. Custom hooks to use the browser’s APIs 2. Exercise: Access the local storage
Our hook usePersistedStorage is only able to handle strings. Can you improve
this hook to accept any value using JSON.stringify and JSON.parse?
Result
Click here to see the solution!
const usePersistedState = (key, initialValue) => {const [value, setValue] = useState(initialValue)useEffect(() => {const existingValue = localStorage.getItem(key)if (existingValue !== null) {try {setValue(JSON.parse(existingValue))} catch (err) {console.error('Error unserializing value.')}}}, [key])const setAndPersistValue = (newValue) => {setValue(newValue)localStorage.setItem(key, JSON.stringify(newValue))}return [value, setAndPersistValue]}