1.0.0 • Published 1 year ago

use-sticky-reducer v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

use-sticky-reducer

Custom hooks to persist React state on browser with the useState and useReducer patterns

Blog Post

Installation

In your React project folder, run:

yarn add use-sticky-reducer
npm install use-sticky-reducer

This is an ES2022 module and requires Node 18 or later.

💻 Example

// App.tsx

import { useStickyReducer } from './useStickyReducer';

// these are the actions for modifying the state that are allowed
type Action = 'increment' | 'double' | 'reset';

// this is a function that takes the state and handles a given Action
// giving us a new state
function reducer(state: number, action: Action): number {
  if (dispatch === 'increment') {
    return state + 1;
  }
  if (dispatch === 'double') {
    return state * 2;
  }
  if (dispatch === 'reset') {
    return 0;
  }
}

export default function App() {
  const [count, dispatch] = useStickyReducer<number, Action>(
    reducer,
    0,
    'my-key',
    (saved: number) => saved - 2
  );
  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={() => dispatch('increment')}>Increment</button>
      <button onClick={() => dispatch('double')}>Double</button>
      <button onClick={() => dispatch('reset')}>Reset</button>
    </div>
  );
}

📚 Usage

useStickyReducer

import { useStickyReducer } from "use-sticky-reducer";

...

const [state, dispatch] = useStickyState(reducer, defaultValue, storageKey, initialization);
PropertyDescription
reducerReducer function
defaultValueThe default value used if storageKey was not previously set
storageKeyUnique string key used to persist data, using your browser's built in localStorage API
initializationOPTIONAL function to transform saved state on hook initialization

useStickyState

import { useStickyState } from "use-sticky-reducer";

...

const [state, setState] = useStickyState(defaultValue, storageKey, initialization);
PropertyDescription
defaultValueThe default value used if storageKey was not previously set
storageKeyUnique string key used to persist data, using your browser's built in localStorage API
initializationOPTIONAL function to transform saved state on hook initialization

With SSR

This package is meant for client-side, browser use. When used in SSR (server-side rendering) it will not fetch the saved state from localStorage, and default the the regular useState or useReducer behavior.