skip to Main Content

I’m curious if i could do something like this:

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

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

For some reason useEffect is not getting triggered when i call setPanelActive function from outside. Should i create some sort of wrapper or context provider in order to make it work?

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to everyone for participating. After some research on what @hatana mentioned, i found a solution - the event bus. It does exactly what I wanted.


  2. If you expected globalThis.setPanelActive to work as setPanelActive with the assignment you are doing, then you are wrong, hooks are designed to work within the scope of a component in this case you have to use a context on a higher lever something like this:

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search