Skip to content

ArthurTent/use-sync-set-state

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

use-sync-set-state

  • This React Hook lets you store the state in localStorage and sync it in between tabs, automagically.

  • use-sync-set-state is a superset of useState i.e, you can always set the state explicitly or via callback function, your call.

  • What's different is that it stores the state in the localStorage and syncs it between tabs by listening to localStorage's storage event.

Installation

yarn add use-sync-set-state

or

npm i use-sync-set-state

Usage

import useSyncSetState from 'use-sync-set-state';

const App = () => {

  React.useEffect(() => {
    setTheme('light');
  }, [])

  const [theme, setTheme] = useSyncSetState('theme', 'dark');

  return <React.Fragment>

  <p data-testid='theme'>{ theme }
  </p>

  // changes will be reflected in all the tabs, without reload.
  <button onClick={e => setTheme((current) => current === 'dark' ? 'light' : 'dark')}>toggle</button>

  <p data-testid='localstorage'>
    {localStorage.getItem('theme')}
  </p>
  
  </React.Fragment>
}

Repository

Explore

About The Author

Website

Github

About

Saves the state in localStorage thus, gives that realtime feel

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 86.9%
  • HTML 13.1%