Mastering React Series: useEffect Hook

useEffect is a Hook in React that allows you to manage side effects in your functional components. A side effect is any state or behavior change that occurs outside of the render function. Some common examples of side effects include:

  • Fetching data from an API
  • Setting and updating a timer
  • Listening to and responding to browser events
  • Updating the document title

With useEffect, you can run these side effects and keep your components clean and focused on rendering UI.

Usage syntax :

useEffect takes two arguments : 

The first argument to useEffect is a function that contains your effect code. This function is called every time your component is rendered, and its purpose is to manage your side effect.

The second argument is an optional argument to useEffect is an array of dependencies. This array is used to tell React when to re-run your effect. There can be three scenarios : 

I. Passing a dependency array with some states: In this case, useEffect will run at the initial render and at every re-render when any of the mentioned states changes.

II. Passing an empty dependency array: In this case, useEffect will run only at the initial render.

III. Passing no dependency array at all: In this case, useEffect runs after every single render (and re-render) of your component.

Cleanup Function

It’s important to understand that side effects can cause unintended consequences if they’re not managed correctly. For example, if you don’t cancel a timer that was set in a previous render, it will continue to run even after the component has been unmounted, causing a memory leak or if we didn’t remove the resize event listener that we added in useEffect, we could end up with multiple event listeners that keep updating the width state even after the component has been unmounted. To prevent these problems, useEffect has a cleanup mechanism. The function you pass to useEffect may optionally return a cleanup function. This function is called when your component is about to be unmounted, or when your effect is about to be re-run, and its purpose is to clean up any state or behavior that your effect created. For example : 

Conclusion

useEffect is a powerful tool for managing side effects in your React components. It's used to run code that affects the state or behavior of your component, and it can be used to handle tasks like fetching data, setting timers, or responding to browser events.

Comments

Popular posts from this blog

Mastering React Series: The Virtual DOM & Reconciliation

Mastering React Series: Class Components Life Cycle Methods

Mastering React Series: Hooks