1

The thing is i want to run some logic only when mounting and also i want to run some other logic when every render/updates. How can we achieve this using hooks in a functional component. If it was a class component i could've use componentDidMount for one time execution and componentDidUpdate for every render.

skyboyer
  • 19,620
  • 7
  • 50
  • 62
  • I think you can use a variation of the answer https://stackoverflow.com/a/53406363/7351882 – AnJo Jun 18 '21 at 06:04
  • Does this answer your question? [Equivalent to componentDidUpdate using React hooks](https://stackoverflow.com/questions/53255951/equivalent-to-componentdidupdate-using-react-hooks) – Vasyl Nahuliak Jun 18 '21 at 06:17
  • These are like some extra logic we adding to achieve such usecase, other than this react itself not providing other options right ? – Ameen Farook Jun 19 '21 at 09:09

2 Answers2

1

Here is a complete explanation:

Equivalent to componentDidMount

useEffect(() => {
  // same as componentDidMount
}, []);

Equivalent to componentDidMount, componentDidUpdate

useEffect(() => {
  // same as componentDidMount and componentDidUpdate
}); 
    

This will be called on change of state variable

const [message, setMessage] = useState('');
useEffect(() => {    
  // Called when value of message changes
}, [message]);
Surjeet Bhadauriya
  • 5,825
  • 3
  • 31
  • 47
  • Ok, i understood this. But what i exactly asking is consider i have 2 functions, function A and function B. Function A should only be called at once while mounting the component and at that time function B should not be called and function B should only called while component updates at that time function A should not call. How can we achieve this using useEffect hook ? – Ameen Farook Jun 19 '21 at 07:23
1

I saw the comment you had for @Surjeet Bhadauriya, there is no specific hook that handle this scenario, but you could easily have a work around this.

Here is an example

const [didMount, setDidMount] = useState(false);

useEffect(() => {
  // your code on didMount;
  setDidMount(true);

}, []);


useEffect(() => {
  if (!didMount)
    return;
  // your code on didUpdate;
});
Alen.Toma
  • 4,571
  • 2
  • 12
  • 27
  • Thanks @Alen.Toma, I also end up with this. I just want to make sure that there is no built in functionality to achieve this. – Ameen Farook Jun 22 '21 at 17:32