1

all! I'm new to React. Currently, I meet a question related to react hooks. The question illustrated below: Design a custom hook to encapsulation useEffect which can perform side-effects operations(such as AJAX request), the designed custom hook can skip the first operation and begin to perform side-effects operations from the second time.

Here I designed one hook, however it is not correct. I do know the key for the hook is how to judge whether this is the first time that the custom hook is called. Someone told me that I should use useRef to count the counter, but I'm not quiet sure how to design it with useRef. Could you guys help me with this question?

function useMyCoustomHook(func, dependencies){
    let counter = 1;
    useEffect(()=>{
       if(counter === 1){
         counter--;
       }else{
         func();
       }
    }, [dependencies])
}
leo0807
  • 941
  • 1
  • 8
  • 21

1 Answers1

1

I removed the dependencies , you should use a ref which remembers its value even if component reRenders unlike your let counter = 1;

function useMyCoustomHook(func, dependencies){
    let counter = useRef(0);
    useEffect(()=>{
       if(counter.current === 0){
         counter.current++;
       }else{
         func();
       }
    }, [dependencies])

   
}
سعيد
  • 1,547
  • 1
  • 14
  • 32
  • 1
    `createRef` returns a new value on every call [ref](https://stackoverflow.com/questions/54620698/whats-the-difference-between-useref-and-createref#:~:text=createRef%20always%20returns%20a%20new,not%20explictly%20storing%20it%20anywhere.). i believe you should `useRef`. or I'm wrong? – Medi Apr 21 '21 at 14:42
  • yeah because when you use normal variable that variable gets recreated verytime the component reloads , but ```useRef```` doesn't behave that way it actually remembers its value even if component reRenders – سعيد Apr 21 '21 at 14:51
  • Understand, Thanks! – leo0807 Apr 21 '21 at 15:30