Table of contents
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.
The following is the proper technique to implement the side effect in our User component:
- We import useEffect from "react".
- In our component, we call it above the returning JSX.
- We provide it with an array and a function as arguments.
Dependencies argument
dependencies argument of useEffect lets you control when the side-effect runs.
(1) Not given: the side effect occurs after each rendering.
(2) An empty array [ ]: After the initial rendering, the side effect is executed once.
(3) Has state values or props: the side-effect only runs when a value of a dependency is altered.