Why useEffect running twice and how to handle it well in React?

πŸš€ Add to Chrome – It’s Free - YouTube Summarizer

Category: N/A

Building WordCloud ...

Summary

No summary available.

Transcript

00:00

hey there welcome back to aast today we are diving into a common recck challenge that many developers face the use effect hook running twice and how to handle it effectively understanding this behavior is crucial for building robust

00:15

applications first let's understand why use effect sometimes runs twice this behavior is most commonly seen in reacts strict mode which was introduced to help developers identify potential problems in their applications when in strict

00:30

mode react intentionally double invokes certain life cycle methods and hooks to help surface any inconsistencies in your code let me show you an example code that will show you the problem it will cause so here on the top I will add a state data set data use State make sure

00:49

to import the use state from react correct this spelling constant okay now I will Define a function fetch data and it would be async and within that I will get a response from Fetch I'm hitting

01:05

the backend server this is just an example fake AP endpoint that we are using just to test it now I will get the Jon and we will return back the response now here I will register my use effect

01:21

make sure to import the use effect from the react and pass it a call back function and then we will pass an empty array here here I I will console. log something like effect running save it also here I will delete

01:39

all of this and here I will add data if data is there then show data loaded otherwise you can show loading and let me remove this double curly braces okay before using this function I will show

01:55

you what happens by default mostly so open the browser and and you can see loading is visible and go to the inspect element of your browser go to the console reload it you can see that effect running is being shown twice so now if we call this function fetch data

02:13

here then this function would be executed twice and it will make the API call twice as well so that is not what we want okay so for example if you reloaded go to the network you would notice that it has hit the backend API twice also once we get the respon we

02:30

want to set data by using that result okay reload it and you can see it is saying data is loaded one of the most common scenarios where double rendering becomes problematic is when making APA calls like you just saw it is hitting the back end API twice so let me show

02:48

you how to handle it properly so in your component you can use this appro approach create a constant effect ran you can name it anything else and and call the function use ref make sure to import it from react and pass it default

03:05

value false okay and in the use effect on the top I will add a check if effect rand. current is equal to false then we will call this okay and also after that

03:20

I will return a function that will set effect rand. current to True okay so now if you reload it you would notice that there is only one console log and also in the network there is only one API

03:36

request that we are sending to the back end when dealing with subscriptions or event listeners proper cleanup is essential so for example let me show you another example let me delete everything from here and this as well this as well

03:52

and on the top I will create a constant window width set window width is equal to use State window do inner width and after that I will create use effect and

04:08

we'll pass it a call back function and within that I will pass another argument that is empty array so that it could call this function only at the time of mounting this component and here we will Define the Handler so constant handle

04:24

resize is equal to okay and here I will set window width window. inner width and here we will add event listener and after that we will clean up function okay here I will check window.

add event

04:42

listener call it and here we will listen to the resize event and in the response we will call our Handler handle resize and here in the cleanup function we will return return a function that will remove the event listener that we

04:58

created above window do remove event listener resize okay and pass it handle resize so we gave it the same Handler function that we passed to register this event so in this way it will remove that event listener and here

05:15

I will simply uh add window width is window width here I will add pixel and now let's see currently it is showing that window width is 1,600 pixel if you reduce it it will update the value in

05:32

the real time and it is also using the good practice now let me show you more advanced solution using aard controller for fetch request so so this is more sophisticated approach for handling API calls so in the app component I will

05:50

again remove everything and on the top I will add constant data set data use State and give it null value as the default and here I will call the use effect with the empty dependency in the

06:06

second argument like this and in this function we will write our logic so very first thing is the constant abort controller is equal to new controller and then constant fetch data

06:21

is equal to async and within that function I will write my function once again try catch we are getting the error in this sketch we will simply check if e do name is equal to about error then we

06:38

will show console. log Fetch abouted and in the else we will show different kind of error console.

error here I will show fetch error and use that error object that we are getting

06:54

now within the try section I will create a constant to get the response from from Fetch I used again the Json placeholder that is a fake API so it will give us the to-do from this ID and we are

07:10

setting the data to our state that we got from the response now at the end after this function definition I will call this fetch data and also I will return a function that will call the function abort controller. abort one

07:27

important thing that is left is here in this fetch function I will pass a second parameter with an object and it will have a property signal and we will give it the abot controller do signal okay

07:42

now here again I will display if data is defined then show data loaded and otherwise show loading okay save it now let's test it inspect element go to the console I made a mistake here I should

07:59

have used the AIT here save it okay now reloaded you can see it is saying data loaded okay and let me show you what is happening here there were two APA calls and one APA call was cancelled automatically so basically the cleanup

08:15

function is very useful here so whenever your component is about to be unmounted or if this use effect is going to be executed again for some reason then it will immediately it and then it will continue okay so this is also very

08:32

useful by the way if uh in the development environment sometimes this repetition happens because of the strict mode so as I mentioned earlier you if you just remove it then it will never execute the logic twice as you can see

08:50

but it is the good practice to keep it in the development mode so that you can take care such situations so that if for some reason if your code tries to run twice you should have implemented such logic that will take care of such situations like this so uh quickly recap

09:08

the best practices so always include cleanup functions when dealing with event listeners subscriptions websocket connections or API calls use appropriate State tracking mechanism us for tracking Mount State Bard controller for fetch

09:23

requests Boolean flags for conditional executions consider alternative approach uh for example re cury or S SWR for data fetching custom hooks for reusable logic State Management libraries for complex data flows understanding and properly

09:39

handling use effects double invocation is crucial for building reliable react applications remember that this behavior is intentional in development mode and helps catch potential issues early by implementing proper cleanup functions and using the techniques we have covered

09:54

you can ensure your effects run run efficiently and your application performs as EXP Ed don't forget to like this video And subscribe to ACH for more react tutorials and programming tips drop your questions in the comments below and I will see you in the next video