A usestate-like react hook for interacting with the browser Local Storage API
npm install use-store-state
import { useStoreState } from 'use-store-state';
const [name, setName] = useStoreState('name', 'Bob');
console.log(name);
// 'Bob'
OR with typescript
import { useStoreState } from 'use-store-state';
const [isDarkMode, setIsDarkMode] = useStoreState<boolean>('darkMode', true);
// ERROR:
// Typescript should throw an error at this
setIsDarkMode('rink and rive');
// SUCCESS:
// This should pass
setIsDarkMode(false);
If no generic is passed, the type is inferred from the initial value, just the same way react useState
works
import { useStoreState } from 'use-store-state';
const [isDarkMode, setIsDarkMode] = useStoreState('darkMode', true);
// ERROR:
// Typescript should also throw an error
setIsDarkMode('rink and rive');
// SUCCESS:
// This should pass
setIsDarkMode(false);
Also allows a callback to be passed as the parameter of setState
.
import { useStoreState } from 'use-store-state';
const [isDarkMode, setIsDarkMode] = useStoreState('darkMode', true);
// Toggle dark mode on/off
setIsDarkMode(prev => !prev);
Type: Infered from the value passed in. If no value is passed, it defaults to undefined
. Also defined by passing in a generic e.g <boolean>
like in the typescript example above.
Type:
React.Dispatch<React.SetStateAction<InferredType>>;
// Where `InferredType` is the type of the passed value or undefined
// OR
React.Dispatch<React.SetStateAction<DefinedType>>;
// Where `DefinedType` is the generic passed to `useStoreState` i.e boolean, string.
Type: any
Added support for SSR. i.e Even though the local storage API is a browser API (window.localStorage
), this should not break when using frameworks like NEXTJS or Vite-SSR which renders the component first on the server before hydrating on the client.