useEffect Hook in React

Raj KishanRaj Kishan
2 min read

Hello everyone.๐Ÿ‘‹ The react hook has a lot of expressions. By writing so little, you can accomplish so much. But starting them is a bit of a challenge, particularly useEffect( ). Learn how to utilise the useEffect( ) hook in this article.

Why use useEffect?

  • You are able to perform side effects in your components using the useEffect Hook.
  • Calculations that the functional component does but which are not intended to affect the output result are referred to as side-effects.

  • Examples include retrieving data, updating the DOM directly, and using timers.

The useEffect() hook takes two arguments:

useEffect (callback, [dependencies]);
  • callback, which is the function containing the side-effect logic.
  • dependencies is an optional array of dependencies.
  • If the dependencies have changed between renderings, useEffect( ) will only perform the callback in that case.

  • Put the logic for the side effect in the callback function, and then use the dependencies parameter to decide when it should be executed.

UKoWlf3-9_cleanup.jpg

The following is the proper technique to implement the side effect in our User component:

  1. We import useEffect from "react".
  2. In our component, we call it above the returning JSX.
  3. We provide it with an array and a function as arguments.

image.png

Dependencies argument

dependencies argument of useEffect lets you control when the side-effect runs.

(1) Not given: the side effect occurs after each rendering.

image.png

(2) An empty array [ ]: After the initial rendering, the side effect is executed once.

image.png

(3) Has state values or props: the side-effect only runs when a value of a dependency is altered.

image.png

0
Subscribe to my newsletter

Read articles from Raj Kishan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Raj Kishan
Raj Kishan