How to create a Custom Hook in React?

Hi, the custom hooks let us to extract component logic into reusable functions and this are normal JS functions that can use other hooks inside of it. 

In that way custom hooks can be used in multiple components. 

I’m going to create a custom hook that fetch data from API depend of the url that we passing: 

Custom hook code:

// Importing react & Dependecies
import { useState, useEffect } from 'react';

// My custom hook to get data from API
export const useFetch = url => {
  // Local state type object
  const [state, setState] = useState({ data: null, loading: true }); // Setting initial state

  useEffect(() => {
    // Set a calllback in Local state
    // To get & return the previous state
    setState(prevState => {
      return {
        data: prevState.data ,
        loading: true
      }
    });

    fetch(url)
      .then(response => response.json())
      .then(data => {
        setState({ data: data, loading: false })
      });

  }, [url, setState]); // Dependecies that useEffect need to start working

  return state;
};

Using the custom hook in my component: you can use the custom hook in more than one component, wherever you need it.

// Dependencies
import React from 'react';

// Styles
import './App.css';

// Custom hooks
import { useFetch } from './customHooks/useFetch';

function App() {
  // Using the custom hook
  const { data } = useFetch(`https://jsonplaceholder.typicode.com/users`);

  return (
    <div className="App">

      <section>
        <h1>Custom hooks with React</h1>

        <section>
        {
          data ?
            <ul>
              {
                data.map((user, i) => {
                  return <li key={`counter-${i}`}>{user.name}</li>
                })
              }
            </ul>
           : 'No data!'
        }
        </section>
      </section>
    </div>
  );
}

export default App;

Result:

By Cristina Rojas.