Skip to content
React hook for sharing state between components.
TypeScript JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
.travis.yml
LICENSE
README.md
jest.config.js
package.json
tsconfig.json

README.md

npm bundle size

🐙 React hook for sharing state between components. Inspired by the provider in flutter.

yarn add @nekocode/use-shared-state

Live example:

Edit useSharedState - example

Simplest usage:

const CounterContext = createSharedStateContext(new SharedState(0));

const ComponentA = () => {
  const counter = useSharedState<number>(CounterContext);
  const onClick = () => {
    counter.setValue(counter.getValue() + 1);
  };
  return (
    <div>
      <div>state: {counter.getValue()}</div>
      <button onClick={onClick}>increase</button>
    </div>
  );
};

const ComponentB = () => {
  const counter = useSharedState<number>(CounterContext);
  return <div>state: {counter.getValue()}</div>;
};

const App = () => {
  return (
    <CounterContext.Provider value={new SharedState(0)}>
      <ComponentA />
      <ComponentB />
    </CounterContext.Provider>
  );
}

Advanced:

// Only get the shared state, never re-render the component
const counter = useSharedState<number>(CounterContext, false);

// Re-render the component only when the new value of shared state is bigger than 1
const counter = useSharedState<number>(CounterContext, (current) => current > 1);

// Re-render the component only when the value of shared state changed
const counter = useSharedState<number>(CounterContext, (current, prev) => current !== prev);

// Use and hook a shared state directly
const sharedState = new SharedState(0);
const conuter = useSharedState<number>(sharedState);
You can’t perform that action at this time.