use-reactive-ls

1.0.6 • Public • Published

Just for fun, I whipped up a custom React hook that makes localStorage reactive. The reactivity isn't stuck in one component — it's global! So whenever localStorage updates, every component using the hook stays in sync. Handy for keeping your app's state consistent across the board.

Example in the online editor

Screen Recording Oct 25

Usage:

import React from 'react';
import { useStore } from 'use-reactive-ls';

export const App = () => {
  // set a name for the variable being saved.
  // it's the 'counter' in this example
  const store = useStore('counter', {
    count: 7,
  });

  return (
    <div>
      <button onClick={() => store.count++}>Inc</button>
      <button onClick={() => store.count--}>Dec</button>
    </div>
  )
}

In other components:

import React from 'react';
import { useStore } from 'use-reactive-ls';

export const MyComponent = () => {
  const store = useStore('counter');

  return (
    <>
      <p>
        Saved value:{' '}
        <span>{store.count}</span>
      </p>
    </>
  );
};

Oh, and don’t forget to eat your broccoli 🥦 — it’s good for you!

Readme

Keywords

none

Package Sidebar

Install

npm i use-reactive-ls

Weekly Downloads

1

Version

1.0.6

License

MIT

Unpacked Size

4.63 kB

Total Files

8

Last publish

Collaborators

  • raullekuna