React Hooks Part 3 😍

React Hooks Part 3 😍

Welcome back again!πŸ˜‡

This is the 3rd article of React Hooks, where we’re learning about different hooks used in React, and today will learn useEffect hook. Before we get started, I'd recommend reading the last blogs of this series React Hooks.πŸ™‚

Let’s learn about useEffect hook

image.png

We use the useEffect hook for calling functions with side effects within our components.

The useEffect hook takes 2 arguments:

callback - a function with side effects

dependencies - an optional array containing dependency values

When our component function runs, the callback will be called if any dependencies have changed since the last time the component function ran.

image.png

This is how the useEffect looks like when we create it

Let us take a look at some of the parameters that can be passed in place of the dependency array, and how it affects the hook itself.

  • Undefined or Skipping the argument

    undefined - the callback is called on every component render (every time the component function runs). Any unrelated state change will trigger the callback function and here we will face the performance issues.

image.png

Here the dependency array is undefined, so our callback will run every time our component function runs, e.g. any time we click the button and useState tells our component to re-run.

  • Empty dependency array

    An empty array simply means that there are no dependencies that will trigger the callback within it. Our code inside the callback will run once when the component gets registered, and that is it.

image.png

Here the dependency array is empty, so our callback will only run once (and permanently set a page background color).

  • With dependency array

We pass an array filled with all the dependencies that should trigger the callback function to run. Anytime the change in the dependencies will trigger the callback function.

image.png

Here, we use useEffect to change the background color to blue when count is a multiple of 5. The callback is called every time the color changes, since color is listed as a dependency.

Awesome! 😍 Hopefully this article helps you.πŸ˜‡

Thank you πŸ™

Did you find this article valuable?

Support Dev Station by becoming a sponsor. Any amount is appreciated!

Β