search

Home  >  Q&A  >  body text

Exposing useState setter function to global scope in React

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粉299174094P粉299174094535 days ago910

reply all(2)I'll reply

  • P粉587970021

    P粉5879700212023-09-12 09:11:45

    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

    reply
    0
  • P粉333186285

    P粉3331862852023-09-12 00:33:05

    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.

    reply
    0
  • Cancelreply