Skip to content

Instantly share code, notes, and snippets.

@burtonator
Last active July 9, 2021 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save burtonator/612348b8f099ec059711b550fecabd26 to your computer and use it in GitHub Desktop.
Save burtonator/612348b8f099ec059711b550fecabd26 to your computer and use it in GitHub Desktop.
useLocalStorageState.ts
import React from 'react';
/**
* Implement a replacement for useState which keeps values in the localStorage.
*
* The idea here is that all calls to use useState can be replaced with
* useLocalStorageState(key, initialValue) and implement the same behavior.
*
* The first time useLocalStorageState is called the value will be initialValue
* because nothing is stored in localStorage.
*
* Each time the user calls the setter (similar to useState) we need to trigger
* component re-render and save the updated value in localStorage.
*
* The next time we are called we should use the value from localStorage.
*
* We should support the following values stored in localStorage:
*
* string, number, object, array
*
* Note that we're using GitHub gists here because there's no compiler. Please
* make sure your code is fully formed, no edge case, clean, etc.
*
* We're not worried about small issues like imports. The main issue is that the
* code is free of bugs and high quality.
*
* @param key The key should be the key used by localStorage
* @param initialValue The initial value to store for the first value.
*/
export function useLocalStorageState<V>(key: string, initialValue: V) {
// TODO: copy/paste this code into a new gist here: https://gist.github.com/
// TODO: implement this code.
}
export const RememberPassword = () => {
// TODO: change this to use useLocalStorageState
const [value, setValue] = React.useState('off');
return (
<input type="checkbox"
value={value}
onChange={event => setValue(event.currentTarget.value)}/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment