1.3.1 • Published 4 years ago

react-shared-state-maker v1.3.1

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

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;
1.3.1

4 years ago

1.2.0

4 years ago

1.2.2

4 years ago

1.3.0

4 years ago

1.2.1

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago