Exposing useState setter function to global scope in React
P粉299174094
P粉299174094 2023-09-11 09:41:15
0
2
859

I'm curious if I can do something like this:

const [panelActive, setPanelActive] = useState(false);
(globalThis as any).setPanelActive = setPanelActive;

useEffect(() => console.log(panelActive), [panelActive])

For some reason, when I call the setPanelActive function externally, useEffect does not get triggered.

Should I create some kind of wrapper or context? Provider to make it work?

P粉299174094
P粉299174094

reply all(2)
P粉587970021

If you expect globalThis.setPanelActive to work the same as setPanelActive in the assignment you are doing, then you are wrong, hooks are designed to work in component scope here In this case, you must use context at a higher level, as follows:

const App = () => {
  export const PanelConext = createContext(); // import createContext
  const [panelActive, setPanelActive] = useState(false);
  //...

  useEffect(() => console.log(panelActive), [panelActive])

  
  return (
    <PanelConext.Provider value={{ panelActive, setPanelActive}}>
      //..
    </PanelConext.Provider>
  );
};
const Component = () => {
  const { panelActive, setPanelActive} = useContext(PanelContext); // import `PanelContext`from App and `useContext` from react
  //...
};

Now when you use setPanelActive from any component, useEffect should fire

P粉333186285

Thank you for your participation. After doing some research on what @hatana mentioned, I found a solution - @hatana . com/DawChihLiou/eventbus-demo" rel="nofollow noreferrer">Event Bus. It does exactly what I want.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template