What is useEffect?

builtbyjosh

builtbyjosh

Posted on August 2, 2021

What is useEffect?

Hooks have become the greatest thing since sliced bread when it comes to programming React components. Everyone has heard of the useState hook. It is one of the biggest selling points of using hooks in React. But another main hook that is available to programmers is called useEffect. But what does it do? How does it help us programmers? And more importantly, how do we use it?

The useEffect hook lets you perform side effects in function components. These side effects are usually a function that is passed into the useEffect hook. You can do many things inside of the useEffect hook actually. One of the most common would be to perform data fetching by connecting to an API and saving the returned data to a variable.

useEffect(()=>{
    console.log(“side effect”)
});
Enter fullscreen mode Exit fullscreen mode

This hook is how you would add lifecycle events, such as componentDidMount, to a functional component. However, the entire lifecycle can be handled within one useEffect hook. There is no need to create the componentDidUpdate or ComponentWillUnmount. So you will have less repeat code in your component.

Sometimes you only want your component to rerender at specific times. To help with this, you can pass an optional second parameter into the useEffect hook. This second parameter is an array. This will only allow a rerender of the component if the array changes. Keeping the array empty will limit the render to only when the component mounts.

useEffect(()=>{
    console.log(“side effect”)
},[]);
Enter fullscreen mode Exit fullscreen mode

The useEffect hook makes it very simple for a developer to create side effects in components without using several different lifecycle methods. You can also use this hook many times in your components. This will help separate unrelated logic and keep your code specific.

💖 💪 🙅 🚩
builtbyjosh
builtbyjosh

Posted on August 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024