Home > Web Front-end > JS Tutorial > body text

Sharing state between unrelated React components

WBOY
Release: 2024-07-17 06:51:30
Original
1116 people have browsed it

Want to show how you can share any serializable data between React components, e.g. client components in NextJS.

We have few unrelated components:

Example app UI

Let's create a object that will contain initial state

export const state: { count: number } = { count: 0 };
Copy after login

We can store data in a Map or a WeakMap, state will be a key to access it. Also, will need a subscribers array.

const stateMap = new WeakMap<object, object>();
const subscribers: (() => void)[] = [];
Copy after login

Now let's write a hook to subscribe to data changes.

export function useCommonState<T extends object>(stateObj: T) {
  // more efficient than `useEffect` since we don't have any deps
  React.useInsertionEffect(() => {
    const cb = () => {
      const val = stateMap.get(stateObj);
      _setState(val!);
    };
    // subscribe to events
    subscribers.push(cb);

    return () => {
      subscribers.slice(subscribers.indexOf(cb), 1);
    };
  }, []);
}
Copy after login

Now let's add logic related to get and set state

  // all instances of hook will point to same object reference
  const [state, _setState] = React.useState<typeof stateObj>(() => {
    const val = stateMap.get(stateObj) as T;
    if (!val) {
      stateMap.set(stateObj, stateObj)
      return stateObj
    }
    return val
  });

  const setState = React.useCallback((newVal: object) => {
    // update value
    stateMap.set(stateObj, newVal);
    // notify all other hook instances
    subscribers.forEach((sub) => sub());
  }, []);

  return { state, setState };

Copy after login

And now can use it in 3 components like

import { state as myState } from './state';
//...

const { state, setState } = useCommonState(myState);

<button
  onClick={() => setState({ count: state.count + 1 })}
  className="p-2 border"
>
  +
</button>
// ...
Component A<div>Count: {state.count}</div>
Copy after login

Final app

You can see how it works here https://stackblitz.com/~/github.com/asmyshlyaev177/react-common-state-example
Or here https://codesandbox.io/p/github/asmyshlyaev177/react-common-state-example/main
Or in github https://github.com/asmyshlyaev177/react-common-state-example

Check out my library for NextJS based on this principle https://github.com/asmyshlyaev177/state-in-url

Tnx for reading.

The above is the detailed content of Sharing state between unrelated React components. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!