Creating custom hooks

  • React
  • Examples
  • Creating custom hooks

React example • 1 min read

  • Async Requests
  • Custom Hooks

useToggle

import { useState } from "react";

function useToggle(initialState = false) {
  const [isActive, setIsActive] = useState(initialState);

  const toggle = () => {
    setIsActive((prevIsActive) => !prevIsActive)
  };

  return {
    isActive,
    toggle
  };
}

export default useToggle;

useFetch

import { useState } from "react";

function useFetch() {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const request = async (url, options) => {
    setData(null);
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(url, options);
      const json = await response.json();
      setData(json);
    } catch (error) {
      setError(error.message);
    } finally {
      setIsLoading(false);
    }
  };

  return {
    data,
    isLoading,
    error,
    request
  };
}

export default useFetch;

Example: https://codesandbox.io/s/9pe0fo