Languages
[Edit]
EN

React - useEffect hook

3 points
Created by:
Lani-Skinner
748

In this article, we would like to show you how to use React useEffect hook.

React useEffect hook is equivalent to the class components lifecycle methods:

  • componentDidMount
  • componentDidUpdate,
  • componentWillUnmount.

The function inside useEffect runs when the component is first rendered and on every array of dependencies update (which is the second, optional argument).

Below examples present:

  • how to import useEffect hook,
  • solution with one argument only (arrow function),
  • solution with two arguments:
    • array of dependencies that is monitored for changes,
    • empty array of dependencies.
  • how to mix useEffect

1. Import

Edit

The first thing you need to do is import useEffect hook the following way:

2. One argument example (only arrow function)

Edit

The arrow function inside useEffect is always executed after:

  • the rendering cycle,
  • props, state or context change,
  • the parent component is rendered.

Runnable example:

3. Two arguments example (arrow function + dependency list)

Edit

The function inside useEffect is executed in two cases:

  • after the component is mounted,
  • after any change of the monitored array of dependencies (in our case on the user change).

Note:

In one useEffect array of dependencies we can put many variables.

Runnable example:

4. Empty array of dependencies example

Edit

In this example, we create useEffect hook with an empty array of dependencies. That tells React to execute the effect only once (at component mount).

Runnable example:

5. We can mix useEffect

Edit

We can also use many useEffect hooks and mix them as we want.

Runnable example:

Related posts

Edit
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - useEffect hook
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join