skip to Main Content

I have variable such as

const [render,setRender] = useState(false);

then, I can use call back like this.

function clickBtn(){
    setRender(true);
}

useEffect(() =>{
    //do something after render is finished.
},[render]);

However I want to change the method by case.

function clickBtn(){
    setRender(true);

}
function clickBtn2(){
    setRender(true);
}

useEffect(() =>{
    //I want to know which Btn is clicked and change the method.
       //doSomething1();        
       //doSomething2();

},[render]);

or like this

function clickBtn(){
    await setRender(true);
    doSomething1();

}
function clickBtn2(){
    await setRender(true);
    //doSomething2();
}

useEffect(() =>{
},[render]);

What is possible and how is the best practice for this method?

2

Answers


  1. Consider setting a value for render that is different per function:

    function clickBtn(){
        setRender(1);
    
    }
    function clickBtn2(){
        setRender(2);
    }
    
    useEffect(() =>{
      if (render === 1) {
        // clickBtn was called.
      else if (render === 2) {
        // clickBtn2 was called.
      }
    },[render]);
    
    Login or Signup to reply.
  2. You need a flag and this can be done using ref.

    import { useEffect, useRef, useState } from "react";
    import "./App.css";
    
    function App() {
      const [bool, setBool] = useState(false);
      const ref = useRef(0);
      const changeVal1 = () => {
        setBool(!bool);
        ref.current = 1;
      };
    
      const changeVal2 = () => {
        setBool(!bool);
        ref.current = 2;
      };
    
      useEffect(() => {
        if (ref.current === 1) {
          console.log("1");
        } else if (ref.current === 2) {
          console.log("2");
        }
      }, [bool]);
    
      return (
        <div className="App">
          <button onClick={changeVal1}>XXX</button>
          <button onClick={changeVal2}>YYY</button>
        </div>
      );
    }
    
    export default App;=
    

    Sandbox

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