Coding task · JavaScript and React course · Module 15: Patterns and Architecture

Practice: useLocalStorage

localStorage stores only strings, so you save the value with JSON.stringify and read it with JSON.parse: without it the number 20 would come back as the string "20", and "20" + 2 gives "202". The function passed to useState is an initializer that React calls only on the first render, so localStorage is not read on every render. The dependency array of the effect says when to save the data again: after the key changes and after the value changes.

Task

Create a useLocalStorage(key, initialValue) hook that works like useState but remembers the value in localStorage. ___BLANK1___: when there is a saved entry under the key, the initializer returns it converted from JSON back into a value (a number comes back as a number). ___BLANK2___: the effect saves the current value converted to JSON under the key. ___BLANK3___: the effect runs again after the key or the value changes. The Settings component uses the hook for the theme, the language and the text size.