Skip to content
This repository has been archived by the owner on Dec 20, 2019. It is now read-only.

A simple way to create shared state using the hook API from React.

License

Notifications You must be signed in to change notification settings

philippguertler/react-hook-shared-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ARCHIVED

I recommend using the Context API instead to allow for better composability.

react-hook-shared-state

A simple way to create shared state using the hook API from React.

Requires at least React 16.7.0

Install

yarn add react-hook-shared-state

Example

import createSharedState from 'react-hook-shared-state'

const [useSharedState, setSharedState] = createSharedState('initial state')

/*
 * The state of every component will be assigned the same value.
 */
const MyComponent = () => {
  const state = useSharedState()
  return (
    <div
      onClick={() => setSharedState(state => state.replace('initial', 'new'))}
    >
      {state}
    </div>
  )
}

API

createSharedState(initialValue)

Returns a tuple with two functions in this order:

  • useSharedState() - Use this in your component. This will return the current state and cause your component to rerender when a new state is set.
  • setSharedState(nextState | (previousState) => nextState) - Call this function to set the new shared state. You can also pass a function which will receive the previous state as a parameter and returns the next state.

About

A simple way to create shared state using the hook API from React.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published