realdennis / persist-hook

Persist Hook : Give me a key, I'll make your React Hook's state persistence.

Home Page:https://www.npmjs.com/package/persist-hook

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Persist Hook

Demo

Give me a key, I'll make your hook's state persistence.

Installation

$ npm install persist-hook

Usage

import PersistHook from "persist-hook";

const config = { key: "$$$normalhook" };
const usePersistState = (initialValue = 0) => {
  const { setPersist, getPersist } = PersistHook(config);
  const [state, setState] = useState(getPersist(initialValue));
  setPersist(state); // it will synchronize state and localstorage
  return [state, setState];
};

const App = () => {
  const [state, setState] = usePersistState(0);
  return (
    <div className="App" style={{ textAlign: "center" }}>
      <p>{state}</p>
      <button onClick={() => setState(state + 1)}>+1</button>
      <button onClick={() => setState(state - 1)}>-1</button>
      <br />
      <button onClick={() => window.location.reload()}>Reload this page</button>
    </div>
  );
};

About

Persist Hook : Give me a key, I'll make your React Hook's state persistence.

https://www.npmjs.com/package/persist-hook

License:MIT License


Languages

Language:JavaScript 100.0%