TechMentorAI

useEffect Hook

in React JS

Published

The useEffect hook is a built-in hook in the React library that allows you to perform side effects in your functional components. Side effects can be anything from data fetching, manually changing the DOM, setting up subscriptions, timers, etc. This hook is essentially a combination of componentDidMount, componentDidUpdate, and componentWillUnmount life cycle methods in the class components.

Imagine useEffect Hook in React JS

Basic Usage of useEffect

The useEffect hook takes two arguments: a function where we write our side effect logic, and an optional array of dependencies. The function gets called after every render, including the first one, when no second argument is provided.

useEffect(() => {
  console.log('This runs after every render');
});

Use of Dependency Array in useEffect

If the second argument (the dependency array) is provided, the function will only be called when the values in the dependency array change. An empty array tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This way it acts like componentDidMount, running the callback function only once after the first render.

useEffect(() => {
  console.log('This runs only once after the first render');
}, []);

Cleanup Function in useEffect

The function passed to useEffect may return a cleanup function. The cleanup functions are a part of the effect hook, they run when a component unmounts and also before re-running the effect due to subsequent re-renders. It's a way of handling componentWillUnmount in functional components.

useEffect(() => {
  console.log('This runs after render');

  return () => {
    console.log('This runs for cleanup');
  };
}, []);

When to use useEffect

Since the useEffect Hook handles both componentDidMount and componentDidUpdate (and componentWillUnmount with cleanup), it's a go-to hook when you want to sync your state/props with some side-effects and clean them up if needed. It’s also commonly used for fetch requests or subscriptions in a React component.

No Time to Read? Learn on the Go!

By reading this article, you've invested 1.36 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

Let's pretend you are playing with your favorite toy set. You have lots of different building blocks, and you can combine them in different ways to create amazing things! React JS is similar. It's like a box of special toys (we call them 'components') for making websites. And you can combine and use these toys any way you want, to build a beautiful website- castle!

Imagine useEffect Hook in React JS

What is a Hook?

You know how you use a hook to go fishing? You use a hook to catch a fish, right? In React, a Hook is a kind of tool that lets you 'catch' and use some special abilities that React has. Like the ability to remember things, or to do something every time a particular thing happens.

What does the useEffect Hook do?

You know when you're playing a video game and every time you get to a certain point, something special happens? Like maybe a hidden treasure box appears or a new character joins the game. Well, the useEffect Hook is a bit like that. In our game-like React, useEffect is a special rule that says 'Whenever this particular thing changes, do this special action'.

An example of useEffect

Let's imagine you're playing a game with a magic door. Every time you open the door, a friendly robot appears who waves at you and then disappears. In React, we can use the useEffect Hook to do something similar! Whenever someone opens a webpage (like opening the magic door), useEffect can make something special happen.

useEffect(() => {
  alert('Hello! A friendly robot waves at you!');
}, []);

More about useEffect

Sometimes you might want to change what happens when you open the magic door. Maybe you want the robot to sing, instead of wave. With useEffect, you can change what happens whenever you want to. That's part of what makes using React JS and Hooks like useEffect so much fun!

No Time to Read? Learn on the Go!

By reading this article, you've invested 1.55 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

For understanding more on hooks, look into React's useState Hook

About author

Roman Y.
Senior Software Engineer at Nike

Why did I decide to launch this website? Drawing from my rich background in interviewing candidates for a variety of developer roles, I've observed a common pattern: many applicants share similar deficiencies in their knowledge during technical interviews. Motivated by this insight, I established this website with the aim of assisting developers in securing their ideal job. Through straightforward and concise articles, my goal is to not only deepen your understanding of programming language nuances but also to equip you with the insights needed to deliver the precise answers interviewers expect. Essentially, you'll be providing the correct response. I encourage you to spread the word about this site on social media platforms. Echoing the wisdom of an Armenian saying: "Do good and cast it into the water."

EXCLUSIVELY

Certain articles only distributed to subscribers through email