DEV Community

kirthinandi
kirthinandi

Posted on

An Introduction to the useEffect Hook

Image description

What are React Hooks?

In React, there are hooks which essentially give function components permission to "hook" into React's features such as state and other methods. There are three general rules when it comes to hooks that should be kept in mind when working with them.

React Hooks Rules:

  1. Hooks can only be called inside React function components
  2. Hooks can only be called at the top level of the function component
  3. Hooks cannot be conditional

Side Effects

A function is considered to have a side effect if it is called and the function causes change outside of the function itself. Examples of common side effects are making requests, fetching data from a database, incorporating a timer, directly updating the DOM, etc.

The useEffect Hook

The useEffect hook available in React allows us to perform some of these side effects mentioned earlier in the function components. To use this hook, it needs to be imported, first.

import React, { useEffect } from "react";
Enter fullscreen mode Exit fullscreen mode

Inside the function component that we want to perform the side effect, we can call the useEffect hook and pass in a callback function which will act like the desired side effect.

function App() {
 //side effect function
  useEffect(
     () => {
       console.log("Hello, I am second");
     }
  );
  console.log("Hi, I am first");
  return (
    <div> 
       <button>Click me</button>
       <input type="text" placeholder="Type here..." />
    </div>
  )
}

Enter fullscreen mode Exit fullscreen mode

When we run the code above, the messages will appear in this order:
1. Hi, I am first
2. Hello, I am second

By passing a console message in the useEffect hook, we are telling the function component to do something after it renders which is console logging the message we want. We can do other things in the hook such as fetching data, creating a timer, or updating the DOM.

useEffect Dependencies

Because the useEffect hook runs on every render meaning it may perform the side effect many times, we need to control this using a dependency. To control the amount of renders, we can incorporate a second parameter, a dependency array, in the useEffect hook.

No Dependency

useEffect(() => {
   //Runs on every render
});
Enter fullscreen mode Exit fullscreen mode

Empty Array

useEffect(() => {
   //Runs only on the first render
}, []);
Enter fullscreen mode Exit fullscreen mode

Props/State Value

useEffect(() => {
   //Runs on the first render 
   //And when dependency value changes 
}, [prop, state]);
Enter fullscreen mode Exit fullscreen mode

Now, that you have the introductory knowledge needed to put the useEffect hook to use, go ahead and try it out! Good luck!

Latest comments (0)