🪝useEffect Hook🪝

🪝useEffect Hook🪝

The UseEffect Hook: Unlimited Power!

So we learned about useState() hook in previous article. Today we are going to learn about most important react js hook which is useEffect()😃.

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

useEffect can be confusing😅 until you understand how it works.

In this article, we’re going to look at lots of useEffect examples so that you understand the mental model and can use it effectively😉 in your own code.

What is useEffect Hook🤔

The useEffect() hook allows us to run side effects on your functional components.

Now you will be thinking what is side effects🤣

Side effects is a general concept about how functions behave which are not predictable. A function is supposed to have side effects when it tries to change something outside of its body. useEffect() also can perform data fetching side-effects using API.

React useEffect is a function that runs for 3 different lifecycles of React components.

These lifecycle methods are following

  • ☝️ componentDidMount
  • ✌️componentDidUpdate
  • 👌componentWillUnmount

The useEffect hook allows us to respond to changes in the component lifecycle. Read about the component lifecycle here.🤓.

The component lifecycle refers to a set of events that occur from the time a component is mounted to the DOM until it is removed. useEffect is most commonly used to execute code when the component is initially rendered, when it is updated, and when it is unmounted.

If anything changes happen and need a side effect on your component then useEffect hook will be called.

Means - when Component

  • Mounts,
  • Unmount,
  • Variable change,
  • State change,
  • Props change or
  • any value changes of component, then this effect hook will work.

UseEffect hook expects a function to do something inside of it.

How do I use useEffect?🤷‍♀️

The useEffect hook accepts ✌️two arguments.

☝️ The first argument is a callback function. This callback function contains the code you want to execute. This is the side-effect you want to make. The useEffect hook executes this callback function after the component is rendered.

✌️The second argument is for an array of dependencies.This argument is optional. Whether you use it or not will depend on when you want the useEffect hook to execute the callback function. If you put a property in this array, useEffect will only be called when that property changes.

UseEffect's basic syntax looks like this:

// Syntax of useEffect hook:
useEffect(callback, [dependencies]);

// Simple example:
// Import useEffect hook from React:
import { useEffect } from 'react'

function App() {
  // Use useEffect hook:
  useEffect(() => {
    // Execute some code.
  }, [])

  // ...
}

You'll start off by importing it from React. Note that we have it inside curly braces because it's a named import.

import { useEffect } from 'react';

As stated before, it's a function. So you'll call that function.

useEffect()

You'll pass an anonymous function into that function as an argument. That's the code you want to run when useEffect is called.

useEffect(() => {
    // executable code here.
    // grab data, update state, etc..
})

useEffect dependency options💥

Without.png

// Option 1 - no dependencies
useEffect(() => {
  // heavy logic that runs after each render
});

// Option 2 - empty dependencies
useEffect(() => {
  // create an event listener, subscription, fetch one-time data
}, []);

// Option 3 - with dependencies
useEffect(() => {
  // fetch data whenever A, B or C changes.
}, [a, b, c]);

Depending on the second argument you have 3 options with different behavior. The logic for each option is:

  1. If not present the effect will run after every render. This option is not commonly used, but it’s useful in some situations like needing to do heavy calculations after each render.
  2. With an empty array [] the effect runs only once, after mounting and the first render. This is great for one-time effects such as creating an event listener.
  3. An array with values [a, b, c]makes the effect evaluate the dependencies, whenever a dependency changes the effect will run. This is useful to run effect when props or state changes, like fetching new data.

Simple Example 💁‍♀️

import React, { useState, useEffect } from 'react';

function CounterOneHook() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
export default CounterOneHook;

Conclusion🙆‍♀️

The React useEffect hook is a hook that brings the functionality of lifecycle methods to functional components🤩. To make this easier, you can think about the useEffect hook as componentDidMount, componentDidUpdate and componentWillUnmount lifecycle methods in one package.

I believe that one of the most important skills to master if you want to become a next-level React developer is understanding the underlying design concepts and best practices of the useEffect Hook.

Hope this helped somebody and thank you for reading!🤗

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!