Home >Web Front-end >JS Tutorial >Understanding and Creating Custom Hooks in React

Understanding and Creating Custom Hooks in React

王林
王林Original
2024-08-30 18:38:10794browse

Understanding and Creating Custom Hooks in React

Table of Contents

  1. Prerequisites
  2. Installation
  3. Introduction
  4. What are Custom Hooks?
  5. When Should You Create a Custom Hook?
  6. Example: Creating a Custom Hook
    • Step 1: Identify the Reusable Logic
    • Step 2: Extracting Logic into a Custom Hook
    • Step 3: Using the Custom Hook
  7. Benefits of Custom Hooks
  8. Best Practices for Custom Hooks
  9. Conclusion

Prerequisites:

Ensure you have the necessary background knowledge in these:

Basic Knowledge of React
Node.js and npm

Installation:

To get started with a new React project using Vite, follow these steps:

i. Open your terminal and run the following command to create a new project:

   npm create vite@latest my-react-app --template react

ii. Navigate into your project directory:

     cd my-react-app


iii. Install dependencies: Install the necessary packages for your project:

   npm install

iv. Start the development server: Run the development server:

    npm run dev

Your React app will now be running, and you can view it in your browser at http://localhost:5173.

Introduction:

What are React Hooks?:

React hooks are special functions that allow you to use state and other React features in functional components. Hooks like useState and useEffect are essential for managing state and side effects.

What are Custom Hooks?:

custom hooks can be described as a way to reuse logic across multiple components. Instead of repeating code, you can encapsulate it in a custom hook, making your components cleaner and your code easier to manage. just like React hooks when using custom hooks ensure that you start your component name with (use followed by the name you want to give the component,e.g useFetchData).useFetchData can be a custom Hook that fetches data from an API and returns it to your component.

understanding Hooks?

Understanding Hooks:
Hooks like useState, useEffect, and useContext allow you to use state and other React features without writing a class. They are building blocks that let you handle component logic in a modular way.

When should you create a custom hook?

Custom hooks let you reuse stateful logic across different components. A simple example is a counter component, that has increment, decrement, and reset functionality, if you need the same logic in multiple components, the logic can be moved to a custom hook. Another commonly used example is a component that fetches data from an API, and if you need the same logic in multiple components, you can move that logic to a custom hook.

Example creating a custom hook

Example: let create a simple counter App with React hook(useState).in app.jsx

Step 1 identify the reusable logic

import React, { useState } from "react";

import "./App.css";

function App() {
  // usestate hooks
  const [counterstate, setCounterstate] = useState(0);

  // function for increment,decrement and reset
  const increment = () => {
    setCounterstate((prev) => prev + 1);
  };
  const decrement = () => {
    setCounterstate((prev) => prev - 1);
  };
  const reset = () => {
    setCounterstate(0);
  };
  return (
    <div className="container">
      <div>
        <h1>Counter App </h1>
        <h2>{counterstate}</h2>
        <div>
          <button onClick={increment}>increment</button>
          <button onClick={decrement}>decrement</button>
          <button onClick={reset}>Reset</button>
        </div>
      </div>
    </div>
  );
}

export default App;

in the code above,the reusable logic include counterstate,initial state(o),increment,decrement and reset function. the increment adds 1 to the initial state while decrement subtract 1 from initial state,while reset resets to first initial state.

Step 2 extracting logic into a custom hook

we can create a folder in src folder named Hooks,then a file called useCouter.jsx for the custom hook as shown below.

import React, { useState } from "react";

const useCounter = (initialvalue) => {
  const [value, setValue] = useState(initialvalue);
  const increment = () => {
    setValue((prev) => prev + 1);
  };
  const decrement = () => {
    setValue((prev) => prev - 1);
  };
  const reset = () => {
    setValue(initialvalue);
  };

  return { value, increment, decrement, reset };
};

export default useCounter;

Step 3 using the custom hook

now, Let's use our custom hook in App.jsx.

import React, { useState } from "react";
import "./App.css";
import useCounter from "./Hooks/useCounter";

function App() {

  const { value, increment, decrement, reset } = useCounter(0);
    return (
    <div className="container">
      <div>
        <h1>Counter App </h1>
        <h2>{value}</h2>
        <div>
          <button onClick={increment}>increment</button>
          <button onClick={decrement}>decrement</button>
          <button onClick={reset}>Reset</button>
        </div>
      </div>
    </div>
  );
}

export default App;

Example 2.

Let's create a custom hook useFetch for all API calls.

import React, { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [url]);
  return { data, error, loading };
};

export default useFetch;

usage

in App.jsx, we can use this custom hook to fetch a username from JSON placeholder as shown below;

import React, { useState } from "react";
import "./App.css";
import useCounter from "./Hooks/useCounter";
import useFetch from "./Hooks/useFetch";

function App() {
  const { value, increment, decrement, reset } = useCounter(0);
  const { data, error, loading } = useFetch(
    "https://jsonplaceholder.typicode.com/users"
  );

  return (
    <div className="container">
      <div>
        <h1>Counter Appp </h1>
        <h2>{value}</h2>
        {loading && <div>Loading....</div>}
        {error && <div>Error: {error.message}</div>}
        {data && data.length > 0 && (
          <div>
            <h2>Username: {data[0].username}</h2>
          </div>
        )}
        <div>
          <button onClick={increment}>increment</button>
          <button onClick={decrement}>decrement</button>
          <button onClick={reset}>Reset</button>
        </div>
      </div>
    </div>
  );
}

export default App;

Benefits of custom hooks

Reusability:

One of the main benefits is reusability. You can use the same custom hook in multiple components, reducing code duplication.

Separation of Concerns:

Custom hooks help you separate the logic from the UI. Your components focus on rendering, while the custom hooks handle the logic.

Cleaner Components:

By moving complex logic to custom hooks, your components become simpler and easier to understand.

Best practices for custom hooks

Naming Conventions:

Custom hooks should start with the word "use" to follow the React naming convention. This also helps in identifying hooks quickly in your code.

Example: useFetch, useForm, useAuth.

Handling Dependencies:

When using hooks like useEffect inside a custom hook, make sure to handle dependencies correctly to avoid bugs or unnecessary re-renders.

Avoiding Unnecessary Re-renders:

Optimize your custom hooks by memoizing values or using hooks like useCallback and useMemo to avoid re-running expensive calculations or re-fetching data.

Conclusion

we've explored the concept of custom hooks and their role in simplifying and enhancing React application development. By creating custom hooks, you can encapsulate and reuse stateful logic, which helps in keeping your components clean and maintainable.

Check out the project on GitHub: My GitHub Repository

The above is the detailed content of Understanding and Creating Custom Hooks in React. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn