use-store-state

A usestate-like react hook for interacting with the browser Local Storage API

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
use-store-state
003.0.07 months ago7 months agoMinified + gzip package size for use-store-state in KB

Readme

use-store-state
!npm packagenpm-imgnpm-url !Build Statusbuild-imgbuild-url !Downloadsdownloads-imgdownloads-url !Issuesissues-imgissues-url !Commitizen Friendlycommitizen-imgcommitizen-url !Semantic Releasesemantic-release-imgsemantic-release-url !Package Sizebundlephobia-imgbundlephobia-url
A usestate-like react hook for interacting with the browser Local Storage API

Install

npm install use-store-state

Usage

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);

API

const state, setState = useStoreState(key, value?)

state

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.

setState

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.

value

Type: any

PERKS

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.