Dev Designer Blog

moon indicating dark mode
sun indicating light mode

Custom React Hooks - Use Persisted Reducer

September 03, 2019

Use Persisted Reducer

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);

useReducer is an alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method. (If you’re familiar with Redux, you already know how this works.)

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

Check out useReducer in the React docs here

usePersistedReducer

redux-persist is a package which is used to persist state from redux to local storage so as to prevent the state from going back to its initial state whenever the page reloads. usePersistedReducer is a custom react hook is a custom react hook that can be used in place of useReducer to persist the state to local storage or any other browser storage provider.

use-persisted-reducer but is a factory that accepts a storage key and an optional storage provider (default = localStorage) and returns a hook that you can use as a direct replacement for useReducer.

Requirement

To use use-persisted-reducer, you must use react@16.8.0 or greater which includes Hooks.

Installation

$ npm i use-persisted-reducer --save

or

$ yarn add use-persisted-reducer

Example

import React from 'react';
import createPersistedReducer from 'use-persisted-reducer';
const usePersistedReducer = createPersistedReducer('state');
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = usePersistedReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}
export default Counter;

You can also pass in your own storage provider

Example

import React from 'react';
import createPersistedReducer from 'use-persisted-reducer';
// defaults to globalThis.localStorage
const usePersistedReducer = createPersistedReducer('state', globalThis.sessionStorage);

You can contribute to the package or give it a star ⭐️ here on Github.


Liked this article, Join the news-letter to get updated on more awesome content

Join the newsletter

powered by TinyLetter

John Ayeni
Personal blog by John Ayeni
I post articles on Front-end tech and
other experiences I have in the tech space.
Comments