react-shared-state-maker
TypeScript icon, indicating that this package has built-in type declarations

1.3.1 • Public • Published

react-shared-state-maker

react hook for share state between the components without use context api.

Attention

The stable version is 1.3.x, earlier versions may not work properly.

Example: make shared state between the components

Make shared state hook in useSharedState.ts / useSharedState.js:

import { makeSharedState } from 'react-shared-state-maker';
 
const useSharedState = makeSharedState('');
 
export default useSharedState;

Put in ComponentA.tsx / ComponentA.js:

import React from 'react';
import useSharedState from './useSharedState';
 
const ComponentA = () => {
  const [value, setValue] = useSharedState();
 
  return (
    <input
      value={value}
      onChange={({ target: { value } }) => setValue(value)}
    />
  );
};
 
export default ComponentA;

And put in ComponentB.tsx / ComponentB.js:

import React from 'react';
import useSharedState from './useSharedState';
 
const ComponentB = () => {
  const [value, setValue] = useSharedState();
 
  return (
    <input
      value={value}
      onChange={({ target: { value } }) => setValue(value)}
    />
  );
};
 
export default ComponentB;

Now, put ComponentA and ComponentB in App.tsx / App.js, let's all!

import React from 'react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
 
const App = () => {
  return (
    <>
      <ComponentA />
      <ComponentB />
    </>
  );
};
 
export default App;

Example: set shared state out of component

Refer to previous section, ComponentA, ComponentB and useSharedState are prepared.

import React from 'react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
import useSharedState from './useSharedState';
 
const [, setValue] = useSharedState.current;
const clearContent = () => setValue(''); // will re-render only components of shared state
 
const App = () => {
  return (
    <>
      <ComponentA />
      <ComponentB />
      <input type="button" value="clear" onClick={clearContent}>
    </>
  );
};
 
export default App;

/react-shared-state-maker/

    Package Sidebar

    Install

    npm i react-shared-state-maker

    Weekly Downloads

    0

    Version

    1.3.1

    License

    MIT

    Unpacked Size

    5.98 kB

    Total Files

    6

    Last publish

    Collaborators

    • fixiabis