Skip to content

TangoPJ/use-reactive-ls

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published