Skip to main content

Command Palette

Search for a command to run...

React Custom Hooks

Published
•3 min read•View as Markdown
React Custom Hooks
A

I am a computer science student who is passionate about web devlopment. I have expertise in MERN stack and is looking forward to sharing my knowledge

What are Custom Hooks

A custom Hook is a JavaScript function only difference is that the name of custom Hook starts with "use"
A custom Hook can call other Hooks.
A custom Hook is just like a regular function, and the word "use" in the beginning tells that this function follows the rules of Hooks.

Rules of Hooks

Rules of Hooks in React:

  1. Only Call Hooks at the Top Level:

    • Do not call hooks inside loops, conditions, or nested functions.

      React relies on the order in which hooks are called to manage their state internally. If hooks are called conditionally or inside loops, the order of hooks calls might change between renders, causing React to mismanage the state and leading to bugs.
      Hence Always use hooks at the top level of your React Component so that hooks are called in the same order each time a component renders.

    • Only Call Hooks from React Functions:

      • Do not call hooks from regular JavaScript functions.
        Hooks are called inside a React function components or from Custom Hooks

Need of Custom Hooks

Custom hooks allow you to extract and reuse stateful logic across multiple components. This means you can encapsulate complex logic in a single function and reuse it wherever needed, reducing code duplication and improving maintainability.

For example

import { useState, useEffect } from 'react';

function 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();
        setData(result);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useFetch;

Now you have a custom Hook useFetch which can be used at multple places wherever you have to get data .

import React from 'react';
import useFetch from './useFetch';
function App() {
  const { data, loading, error } = useFetch('https://api.example.com/data');
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return (
    <div>
      <h1>Fetched Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
export default App;

Note : When you create a custom hook in React, it's a way to reuse logic, not the actual state.

Does custom hook share state

Suppose you have a custom Hook useFetch and you have to use this in multiple places ,Now if it is being used at multiple places will it give you state management issues?
No, components using the same custom hook do not share state. Custom hooks are designed to reuse stateful logic, but each time a custom hook is used, the state and effects inside it are completely isolated and independent for each component.

import React from 'react';
import useFetch from './useFetch';
function UserList() {
  const { data, loading, error } = useFetch('https://api.example.com/users');
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return (
    <div>
      <h1>User List</h1>
      <ul>
        {data.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

function PostList() {
  const { data, loading, error } = useFetch('https://api.example.com/posts');
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return (
    <div>
      <h1>Post List</h1>
      <ul>
        {data.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

In this example, UserList and PostList both use the useFetch hook, but they do not share the same state:

  • UserList fetches and manages its own state for the user data.

  • PostList fetches and manages its own state for the post data.

Each component has its own isolated state and effects. Changes in the state of one component do not affect the other. This isolation ensures that components using the same custom hook can operate independently without any conflicts.

Thanks for Reading!!!

Kindly Share, like and comment your thoughts!

Follow me on LinkedIn