What is custom hooks in React.js

What is custom hooks in React.js

Custom hooks in React let you take logic you use over and over and put it into separate functions. These functions can use React hooks, but they aren't components. Custom hooks help you use the same logic in many places, making your code neater, easier to read, and easier to keep up with.

Here are some key points about custom hooks:

  1. Naming Convention: Custom hooks must start with "use" just like React's own hooks. This shows that it's a hook and should be used with the use keyword.

  2. Reusability: Custom hooks let you put complex logic and stateful behavior into one function. This means you can use the same logic in many components without writing it again.

  3. Composition: Custom hooks can use other hooks inside them. This lets you build complex behaviors from simpler ones, making your code modular and easy to put together.

  4. No JSX: Custom hooks don't return JSX elements. They usually return values, state, or functions that components can use.

  5. No Side Effects in Conditionals or Loops: Like built-in hooks, custom hooks shouldn't have side effects inside conditions or loops. Always use hooks at the top level of a functional component or another hook.

Here's an example of a custom hook that fetches data from an API:

import { useState, useEffect } from 'react';

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error('Network response was not ok');
        const result = await response.json();
      } catch (error) {

  }, [url]);

  return { data, loading, error };

export default useFetch;

You can then use this custom hook in your components:

import React from 'react';
import useFetch from './useFetch'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  const { data, loading, error } = useFetch('https://api.example.com/data');

  if (loading) {
    return <div>Loading...</div>;

  if (error) {
    return <div>Error: {error.message}</div>;

  return (
      <h1>Data from API:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>

export default MyComponent;

Custom hooks let you package and reuse logic across components, making your React applications more maintainable and your code easier to reuse.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!