DEV Community

Kemi Owoyele
Kemi Owoyele

Posted on

react js useEffect hook

The useEffect hook is used to handle function side effects in React. A function side effect in JavaScript is any effect outside the function’s local variable. Examples of function side effect include;
I. Making network request
II. Manipulating the DOM
III. Fetching data from an API
IV. Changing the value of a variable or an object that is outside the scope of the function
V. setInterval or setTimeout operations
VI. Accessing or modifying web API’s
The use effect hook runs every time the component is rendered. Remember that apart from the initial render when a component first load to the DOM, the component is re rendered whenever there is a state change.

How to use the useEffect hook

First of all, we need to;
• Import useEffect from react
import { useState, useEffect } from "react";
• Somewhere in your component, before the return statement, call the useEffect hook with two arguments.

• The first argument is a callback function containing instructions we want to execute whenever the useEffect is triggered.

• The second optional argument is an array of dependencies that will determine when the useEffect will run. If the array is empty, the useEffect will run only once after the initial render. If the dependency argument is omitted, the useEffect will trigger whenever there is a state change. If values are provided inside the dependency array, the useEffect will be triggered only when there is a state change in any of those values.

• Syntax

useEffect(()=>{
    // excecute side effect
  }, [an array of values that the effect depends on]);

Enter fullscreen mode Exit fullscreen mode

*Example *

import { useState, useEffect } from "react";

const Home = () => {
  const [name, setName] = useState("");
  const changeName = () => {
    const userName = prompt("what is your name");
    setName(userName);
  };

  useEffect(() => {
    alert(`welcome ${name}`);
  }, [name]);

  return (
    <>
      <h1>welcome {name}</h1>
      <button onClick={changeName}>click me</button>
    </>
  );
};

export default Home;



Enter fullscreen mode Exit fullscreen mode

Top comments (0)