Search code examples
reactjsreact-hooksuse-effectuse-context

How trigger function after react context hook updated


I'm trying to call a function after the "context hook" from react is updated. Tried the code below:

const MyComponent = () => {
  [context] = useContext(MyContext);
  
  function updateContext():void {
    context = "someNewContext";
  }
  
  function anotherFunction():void {
    console.log("success!");
  }
  
  useEffect(() => {
    anotherFunction();
  }, [context]);
  
  return (
    <button onClick={updateContext}>update</button>
  );
}

export default MyComponent;

Solution

  • Now i see what was wrong... First i need a wrapper with useState, like this:

    const App = () => {
      const [context, setContext] = useState("initial value");
      const value = { context, setContext };
    
      return (
        <MyContext.Provider value={value}>
          <MyComponent />
        </MyContext.Provider>
      );
    };
    

    And then on component:

    const MyComponent = () => {
      {context, setContext} = useContext(MyContext);
    
      function updateContext():void {
        setContext("Some new context");
      }
    
      function anotherFunction():void {
        console.log("success!");
      }
    
      useEffect(() => {
        anotherFunction();
      }, [context]);
    
      return (
        <button onClick={() => {updateContext()}}>update</button>
      );
    }
    
    export default MyComponent;