React Hooks are the functions which "hook into" React state and lifecycle features from function components. Hooks allows you to manipulate state and other React feature without writing a class. Let's talk about widely used hook
useEffect hook at a glance 🧵👇🏻
useEffect hook is the heart of React functional components
If you're familiar with class components then you might know that we have various lifecycle methods but in functional components, we don't have any lifecycle methods. Instead we have a powerful hook called useEffect
By using useEffect, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates
So let's start by understanding the syntax first
3/15
useEffect take two parameters, first is a function and second is an array.
The function inside the useEffect will run every single time component re-render. Consider this piece of code and check the output in next tweet
{ 4 / 15 }
As you can see in the output the function is executed every single time my component re-render
{ 5 / 15 }
But let's say if I add some dependency in the array and pass the array as second parameter then useEffect will only run when the value of dependency array change.
For example, let me modify the code little bit so that you can understand it better
{ 6 / 15 }
As you can see when I click on the re-render button, our useEffect run this is because I have passed render state inside dependency array
{ 7 / 15 }
🚨 Here's an important thing to note is that if you pass an empty array then it will only run on once.
No matter how many times you render your component, the useEffect will run only once because the value of empty array never going to change
{ 8 / 15 }
In useEffect we can also perform clean up
If we return a function within the method, this function perform basically a clean up of what we did last time.
Awesome! I think we have covered everything related to useEffect hook. It is little tough so try to play around with the code. I hope you like this thread ❤️
Peace out 😉
• • •
Missing some Tweet in this thread? You can try to
force a refresh