On Load Hook in React Functional Component – HTTP Call on Component Load

How to execute some code when the functional component is loaded in React? How we can bind state variable callback in React functional component? These are few questions we will discuss in this tutorial with examples and demo application.

In applications that are data-driven like React, we load data when a view or page is loaded. In react we can create either class or function based components. In a class-based component, we have componentWillMount() or componentDidMount() hooks that can be used to execute any function when the component is going to load or loaded into view.

With support for the latest functional component, we can use the useEffect() hook to load data or execute a function at on load event.

Ideally, the useEffect() a hook is executed whenever there is a change in the internal or dependent props in the functional component. But we will discuss how to limit the execution-only once when the component is loaded.

The useEffect() hook is available for functional components, they are bound to state change events. The second argument of the hook can be used to limit its execution for a particular state. We can have multiple useEffects() hooks in a single functional component. Each useEffect() hook is executed at least once on component load.

How to use useEffect hook in a functional component?

To start using the hook you need to import the useEffect function from React as shown below:

import React, { useEffect } from "react";
import "./App.css";

function App() {

  useEffect(() => {
    console.log("Exucute useEffect");
  });

  return (
    <div>
     App Functional Component
    </div>
  );
}
export default App;

How to Load Dynamic Data using HTTP Fetch in Functional Component?

Ideally, the useEffect() hook is executed every time whenever the state is changed, but we can add the employ value to the array parameter to call it only once the component is loaded at the app start.

useEffect(() => {
    console.log("Executed only once!");
  }, [""]);

In the following example, we are loading some data from a remote server using HTTP get call and mapping the list in the JSX template. Here we have two state variables search and fitlerList but useEffect() with fetch HTTP called only once as we added the empty value in the array.

import React, { useEffect, useState } from "react";
import "./App.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

let MY_LIST = [];

function App() {
  const [search, setSearch] = useState("");
  const [filterlist, setFilterlist] = useState(MY_LIST);

  function fetchData() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        MY_LIST = data;
      });
  }

  function onKeyUpHandler(e) {
    setSearch(e.target.value.toLowerCase());
  }

  useEffect(() => {
    console.log("executed only once!");
    fetchData();
  }, [""]);

  return (
    <div className="container mt-5">
      <input
        id="searchFilter"
        type="text"
        className="form-control"
        defaultValue={search}
        placeholder="Enter ID or Name"
        onKeyUp={onKeyUpHandler}
      />
      <ul className="list-group">
        {filterlist.map((item, key) => (
          <li className="list-group-item" key={key} value={item.id}>
            {item.id}) {item.title}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

You can test by removing [""] from useEffect() that will start executing on every key up event on input.

Alternatively, you can add one more useEffect() to watch the search state value as shown below:

useEffect(() => {
    console.log("useEffect");
    fetchData();
  }, [""]);

  useEffect(() => {
    console.log("Value of search changed!");
  }, [search]);

 

Hope this will be helpful!

 

Leave a Reply

Your email address will not be published. Required fields are marked *