use-remember-state
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

useRememberState

github-version npm-version install-size publish-size

React Hook designed to extend the useState hook using localStorage as the persistance method on the browser, ready for TypeScript environments too.

Installation

yarn add use-remember-state

or

npm install --save use-remember-state

Why

When you use useState you need to give a default value, usually it's just used as a placeholder, but what if you want that value to be data you already put before?, the common solution is to use the default value calling localStorage.getItem(name), but of course you need to call localStorage.setItem(name, value) before, and this call should be handled everytime the value you want to save is changed. And you have to keep in mind that if you have SSR implemented, there is no localStorage on the server, so you need fallbacks, so clearly it just becomes a nightmare and tons of repetitive code.

All that problem is solved using the custom hook useRememberState

Usage

The return values from the hook are exactly the same as useState, but the arguments should be first a consistent name which is going to be used as key for localStorage, and after that a default value, which is going to be used as fallback for the first time render or server side rendering.

import React, { FunctionComponent } from "react";
import { useRememberState } from "use-remember-state";
 
const HelloWorld: FunctionComponent = () => {
  const [data, setData] = useRememberState("HelloWorldInput", "");
 
  return (
    <div>
      <p>This input remembers the input after every reload</p>
      <input
        value={data}
        onChange={({ target: { value } }) => {
          setData(value);
        }}
      />
    </div>
  );
};

Keep in mind that the name should be unique around the app.

For server side rendering the default value is only going to be used for the first render, but after the component is mounted on the browser, it will try to fetch again to localStorage looking for the data.

SSR

Handling SSR correctly and efficiently with localStorage has it's problems, so in order to prevent setting state twice (therefore, rendering an extra time) and at the same time preventing the warning "useLayoutEffect does nothing on the server" when using SSR you have to specify an optional third argument:

useRememberState(name, defaultValue, { SSR: true });

Debounce

Accessing localStorage is computationally expensive, in order to improve performance all the calls to localStorage are debounced, the default amount of delay is 500 ms, you can change it to any amount, or set it to 0 to make the calls synchronously.

useRememberState(name, defaultValue, { debounceWait: 100 });

License

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Readme

Keywords

none

Package Sidebar

Install

npm i use-remember-state

Weekly Downloads

3

Version

2.0.0

License

MIT

Unpacked Size

25.6 kB

Total Files

13

Last publish

Collaborators

  • pablosz