React – How to create a custom hook?

Example 1

import { useState } from "react";

const useJokes = () => {
  const [joke, setJoke] = useState("No joke.");
  const onRequest = () => {
    fetch("https://api.chucknorris.io/jokes/random")
      .then(response => response.json())
      .then(joke => setJoke(joke.value))
      .catch(err => err);
    };
    return { joke, onRequest };
};

export default useJokes;
const { joke, onRequest } = useJokes();

<div>
  <h4>{joke}</h4>
  <button onClick={onRequest}>Click to see a new joke.</button>
</div>

Example 2

import { useState } from "react";

const useJokes = () => {
  const [joke, setJoke] = useState("No joke.");
  const [loading, setLoading] = useState(true);
  const onRequest = () => {
    fetch("https://api.chucknorris.io/jokes/random")
      .then(response => response.json())
      .then(joke => {
        setJoke(joke.value)
        setLoading(false)
      })
      .catch(err => {
        console.log(err)
        setLoading(false)
      })
      .finally(() => {
        setTimeout(() => {
          setLoading(false)
        }, 2000)
      });
    };
    return { joke, loading };
};

export default useJokes;
const { joke, loading } = useJokes();

if (loading) {
  return <div>
    <Spinner />
  </div>
} else {
  return <div>
    <h4>{joke}</h4>
  </div>
}

Be the first to comment

Leave a Reply

Your email address will not be published.


*