reactjs
  1. reactjs-custom-hooks

ReactJS Custom Hooks

Custom Hooks are a new feature in React 16.8 that allow you to reuse stateful logic between React components. With Hooks, you can extract the code that creates stateful logic into reusable functions, allowing you to easily share that code between components.

Syntax

The syntax for using a custom hook is similar to that of using any other built-in hook.

import { useCustomHook } from './CustomHook';

function MyComponent() {
  // Use the custom hook
  const { data, error } = useCustomHook();

  return (
    <div>
      {error && <span>{error}</span>}
      {data && <span>{data}</span>}
    </div>
  );
}

Example

Let's take an example of a custom hook that fetches data from an API endpoint.

import { useState, useEffect } from 'react';

function useApi(url) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(url);
        const json = await response.json();
        setData(json);
      } catch (error) {
        setError(error.message);
      }
    }
    fetchData();
  }, [url]);

  return { data, error };
}

export default useApi;

Output

When used in a component, the useApi hook will return the data and error state variables.

const { data, error } = useApi(`https://api.example.com/data`);

Explanation

This custom hook uses the regular React Hooks useState and useEffect to manage state. It takes in a URL as a parameter and fetches data from that URL using the fetch API.

The useEffect hook is used to ensure that the data is fetched only once, when the component mounts. The useEffect hook also ensures that the data is re-fetched if the url parameter changes.

The hook returns an object containing the data and error state variables, which can be used in the component that calls the hook.

Use

Custom hooks can be used in any React component, just like the built-in React Hooks.

Typically, you would create your custom hooks in a separate file, and import them into the component that needs them.

import useApi from './hooks/useApi';

function MyComponent() {
  const { data, error } = useApi('https://api.example.com/data');

  return (
    <div>
      {error && <span>{error}</span>}
      {data && <span>{data}</span>}
    </div>
  );
}

export default MyComponent;

Important Points

  • Custom Hooks are just normal functions, prefixed with the word use.
  • Custom Hooks can use any built-in React Hook, but not conditionally.
  • Custom Hooks can be exported and reused across different React components.
  • Custom Hooks should be used to abstract complex stateful logic and make it reusable.
  • Custom Hooks should not be overused, as they can add additional complexity to your codebase.

Summary

Custom Hooks are a powerful feature in React that allow you to extract stateful logic into reusable functions. With Custom Hooks, you can easily share stateful logic across different React components, making your codebase more maintainable and scalable. While they come with a few limitations, such as not being conditionally callable, they provide a significant boost in code reusability.

Published on: