Skip to content

A react hook that is exactly like useState but state is shared instead

License

Notifications You must be signed in to change notification settings

alradadi/create-shared-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

create-shared-state

A hook that has the exact same API as useState but the state can be shared between components instead.

Motivation

Most of the state management tools out there force you to create and initialize your shared state outside components and custom hooks. Well, sometimes the initial state isn't available until the component calls another hook. The hook provided by create-shared-state can be used exactly like the default useState except that state is shared between components.

Installation

yarn add create-shared-state

Usage

  • Example 1
import { create } from 'create-shared-state';

const useSharedState = create();

const useCounter = () => useSharedState(0); // the custom hook useCounter can be used in any component

const [counter, setCounter] = useCounter() // use in components

  • Example 2
import { create } from 'create-shared-state';
import { useForm } from 'react-hook-form';


const useSharedState = create();

/**
* The logic for this form and its methods is accessible from anywhere.
* This makes it possible for one component to handle updating and validating the form,
* and another component to handle the submission for examaple. 
*/
const useOnboardingForm = () => {
  const methods = useForm()
  
  const [sharedMethods] = useSharedState(methods)

  return sharedMethods
}

License

MIT

About

A react hook that is exactly like useState but state is shared instead

Topics

Resources

License

Stars

Watchers

Forks