Local Storage II - hook
Medium
3
36.5% Acceptance
You need to create a custom hook called useLocalStorage(key, initialValue)
that can be used to store and retrieve data from local storage. You should use the key
prop as the key for the data in local storage and initialValue
as the initial value.
The hook should return an object with two properties:
- the current value of the data, which should be initialized to the value stored in local storage (if it exists), or the
initialValue
argument (if it doesn't) - a function that can be used to update the value of the data in local storage
Every time the value of the data is updated, the hook should update the corresponding value in local storage.
Please see the example below for the required return object.
We have already written some starting code for you.
Instructions
- You do not need to edit the App component. Tests will be scoring only the
useLocalStorage
hook.
Example test cases
{ value: string, setValue: function }
Hints
- Use the
useState
hook to create a state variable for the value of the data to be stored in local storage. Initialise the state variable using theuseState
hook's initialiser function. - Use the
useEffect
hook to write the data to local storage whenever it changes. Make sure to pass the value and the key touseEffect
's dependencies array to ensure that it only updates when the value changes.