How i met useEffect().

How i met useEffect().

How useEffect() solved my problem of not getting into the infinite loop of re-rendering page.

So when I started working on react.js, by this I mean learning react.js, I was pretty comfortable with useState() Hook. basically, useState() is something that acts as a variable in react.js for a component and its updation also causes the re-rendering of the current web page or component.

let's get back into the story

So I was trying to develop a youtube clone kind of project where I am supposed to fetch the data from youtube data Api and render them on the screen based on the text search from the user. initially, I need some data to be rendered on my screen even before the user starts. So the process was to get the API Key and end-point, I followed the step and got both.

My plan was to make a call to the server, get the initial data as soon as the page loads and store it in a variable which is useState. Remember me mentioning, that the page re-rendering happens when the state gets updated, But I recklessly made a call to the server and waited for something would show up in the console as I did console.log to see whether I am getting the data or not.

But got this.

Error Too many re-renders infinite loop in React Js

That's when useEffect came to recuse me

uhh.. referring useEffect hook as an iron man here... hehe

useEffect is a kind of hook that only runs when the component/page is rendered for the first time, if the page rendered for the second time useEffect() don't care about it just like my Ex-girlfriend.

So I wrote my initial data fetching logic in this hook.

useEffect(()=>{
    //logic to get the data. 
    // you can update the state.
},[])

It takes the two arguments one is a function and the other is a dependency, meaning depending on a state updation the useEffect() runs again, you can put an empty list if you don't want any dependency for your useEffect(). But remember cleaning up the old useEffect call is also important. For that, you can simply return a callback function.

useEffect(()=>{
    //logic to get the data. 
    // you can update the state.
return ()=>{}
},[])

So whenever the useEffect run again first it executes the return statement which in a way acts as the clean-up for useEffect(). You can write a console.log in that callback and see.

that's pretty much me knowing about useEffect(), let's talk about other hooks in react in the latter articles. Thanks for reading till the end.