Understanding the UseEffect() Hook in React

Understanding the UseEffect() Hook in React

ยท

2 min read

what are Hooks?

Hooks are the functions which "hook into" React state and lifecycle features from function components.

What to note about react hooks

  1. Hooks don't work in class based component
  2. Hooks run in order
  3. useEffect Hook is run (and cleans up) on every render.
  4. In useEffect hook we pass in a function that we want React to run every time our component gets rendered or updated.

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.

cleanup.png

example

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

function App() {
  const [loading, setLoading] = useState(true);
  const [tours, setTours] = useState([]);

  const fetchTours = async () => {
    setLoading(true);
    try {
      const response = await fetch(url);
      const tours = await response.json();
      setLoading(false);
      setTours(tours);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };
  useEffect(() => {
    fetchTours();
  }, []);
  return (
    <div>
      {tours.map((tour) => (
        <div key={tour.id}>
          <p>tour.name</p>
          <p>tour.price</p>
          <p>tour.info</p>
        </div>
      ))}
    </div>
  );
}

You don't understand how useState works? ๐Ÿ˜Ÿ๐Ÿ˜Ÿ๐Ÿ˜Ÿ

setting state in functional component