Update formatting

This commit is contained in:
Isabelle Viktoria Maciohsek
2022-01-30 19:41:17 +02:00
parent e7988c0065
commit 9661870d03
6 changed files with 9 additions and 9 deletions

View File

@ -8,12 +8,12 @@ lastUpdated: 2021-10-13T19:29:39+02:00
Returns a stateful value, persisted in `localStorage`, and a function to update it.
- Use the `useState()` hook to initialize the `value` to `defaultValue`.
- Use the `useRef()` hook to create a ref that will hold the `name` of the value in `localStorage`.
- Use the `useRef()` hook to create a ref that will hold the `name` of the value in `Window.localStorage`.
- Use 3 instances of the `useEffect()` hook for initialization, `value` change and `name` change respectively.
- When the component is first mounted, use `Storage.getItem()` to update `value` if there's a stored value or `Storage.setItem()` to persist the current value.
- When `value` is updated, use `Storage.setItem()` to store the new value.
- When `name` is updated, use `Storage.setItem()` to create the new key, update the `nameRef` and use `Storage.removeItem()` to remove the previous key from `localStorage`.
- **Note:** The hook is meant for use with primitive values (i.e. not objects) and doesn't account for changes to `localStorage` due to other code. Both of these issues can be easily handled (e.g. JSON serialization and handling the `'storage'` event).
- When `name` is updated, use `Storage.setItem()` to create the new key, update the `nameRef` and use `Storage.removeItem()` to remove the previous key from `Window.localStorage`.
- **Note:** The hook is meant for use with primitive values (i.e. not objects) and doesn't account for changes to `Window.localStorage` due to other code. Both of these issues can be easily handled (e.g. JSON serialization and handling the `'storage'` event).
```jsx
const usePersistedState = (name, defaultValue) => {