Custom Hooks in React: Reusing Logic Across Components
Custom Hooks in React
A Custom Hook is a JavaScript function that allows you to reuse stateful logic across multiple components in a React application. Custom hooks are a powerful tool for encapsulating logic that can be shared among components, keeping the components clean, and promoting code reusability.
Custom hooks are prefixed with use, to follow React’s convention, and can use other hooks inside them (such as useState, useEffect, useContext, etc.).
Why Use Custom Hooks?
Custom hooks provide several benefits:
- Code Reusability: They allow you to extract reusable logic from your components. If you have logic that needs to be shared among multiple components, you can extract it into a custom hook.
- Separation of Concerns: By moving complex logic out of components, custom hooks can help keep components more focused on rendering UI, which improves readability and maintainability.
- Abstraction: They provide a way to abstract complex logic, making your components cleaner and easier to understand.
How to Create a Custom Hook
To create a custom hook, follow these steps:
- Write a function: The function should contain the logic you want to reuse.
- Use built-in hooks: Inside the function, you can use other React hooks such as useState, useEffect, or any other hooks to manage state or side effects.
- Return values: Return the necessary state, functions, or values from the custom hook to be used in the component.
Basic Example of a Custom Hook
Here is a simple example of a custom hook that manages the mouse position:
import { useState, useEffect } from 'react'; // Custom Hook to track mouse position const useMousePosition = () => { const [position, setPosition] = useState({ x: 0, y: 0 }); useEffect(() => { const updatePosition = (event) => { setPosition({ x: event.clientX, y: event.clientY }); }; // Add event listener for mouse movement window.addEventListener('mousemove', updatePosition); // Clean up the event listener return () => { window.removeEventListener('mousemove', updatePosition); }; }, []); return position; }; export default useMousePosition;
Explanation:
- The custom hook useMousePosition tracks the mouse position on the screen.
- It uses useState to manage the state of the mouse coordinates (x and y).
- It uses useEffect to add an event listener for the mousemove event and cleans it up when the component is unmounted or the effect is re-run.
- The hook returns the mouse position (x and y), which can be used by any component that imports and calls useMousePosition.
Using the Custom Hook in a Component
Now, you can use this custom hook in any component to access the mouse position:
import { useState, useEffect } from 'react'; // Custom Hook to track mouse position const useMousePosition = () => { const [position, setPosition] = useState({ x: 0, y: 0 }); useEffect(() => { const updatePosition = (event) => { setPosition({ x: event.clientX, y: event.clientY }); }; // Add event listener for mouse movement window.addEventListener('mousemove', updatePosition); // Clean up the event listener return () => { window.removeEventListener('mousemove', updatePosition); }; }, []); return position; }; export default useMousePosition;
Explanation:
- The MouseTracker component uses the useMousePosition custom hook to access the mouse position.
- Whenever the mouse is moved, the position is updated, and the component re-renders to display the new coordinates.
Advanced Example: Custom Hook for Form Handling
You can create custom hooks for more complex logic, like form handling.
import React from 'react'; import useMousePosition from './useMousePosition'; const MouseTracker = () => { const position = useMousePosition(); // Using the custom hook return ( <div> <h2>Mouse Position:</h2> <p>X: {position.x}, Y: {position.y}</p> </div> ); }; export default MouseTracker;
Explanation:
- The useFormInput hook takes an initial value and returns the input value and a handleChange function.
- The hook can be used in any form component to manage form input state.
Using the Form Hook in a Component
Now, you can use useFormInput in a form component:
import { useState } from 'react'; // Custom Hook to handle form input const useFormInput = (initialValue) => { const [value, setValue] = useState(initialValue); const handleChange = (event) => { setValue(event.target.value); }; return { value, onChange: handleChange, }; }; export default useFormInput;
Explanation:
- The useFormInput hook is used to handle the state and change events for both the name and email inputs.
- The handleSubmit function logs the form values when the form is submitted.
Rules for Custom Hooks
Custom hooks follow the same rules as React hooks:
- Only call hooks at the top level: Do not call hooks conditionally or inside loops.
- Only call hooks from React functions: Custom hooks can only be called from React functional components or other custom hooks.
- Start with use: Custom hooks must start with the use prefix to differentiate them from regular JavaScript functions.
Using Custom Hooks for Side Effects
Custom hooks can also be used to handle side effects, like fetching data.
import React from 'react'; import useFormInput from './useFormInput'; const MyForm = () => { const nameInput = useFormInput(''); const emailInput = useFormInput(''); const handleSubmit = (event) => { event.preventDefault(); console.log('Name:', nameInput.value); console.log('Email:', emailInput.value); }; return ( <form onSubmit={handleSubmit}> <div> <label>Name:</label> <input type="text" {...nameInput} /> </div> <div> <label>Email:</label> <input type="email" {...emailInput} /> </div> <button type="submit">Submit</button> </form> ); }; export default MyForm;
Explanation:
- useFetchData is a custom hook that fetches data from an API.
- It manages the data, isLoading, and error states.
- The hook is reusable in any component that needs to fetch data from an API.
Using the Fetch Data Hook in a Component
Here’s how you can use the useFetchData hook in a component:
import { useState, useEffect } from 'react'; // Custom Hook to track mouse position const useMousePosition = () => { const [position, setPosition] = useState({ x: 0, y: 0 }); useEffect(() => { const updatePosition = (event) => { setPosition({ x: event.clientX, y: event.clientY }); }; // Add event listener for mouse movement window.addEventListener('mousemove', updatePosition); // Clean up the event listener return () => { window.removeEventListener('mousemove', updatePosition); }; }, []); return position; }; export default useMousePosition;
Explanation:
- The DataComponent uses the useFetchData custom hook to fetch data from the API.
- The component handles loading, error, and displaying the fetched data based on the state returned from the custom hook.
Summary of Custom Hooks
- Custom hooks allow you to encapsulate and reuse logic in your React application.
- They help keep your components clean by abstracting away complex logic.
- Custom hooks can use built-in hooks like useState, useEffect, and others, and they follow the same rules as React hooks.
- Common use cases for custom hooks include managing form inputs, fetching data, handling side effects, and more.
The above is the detailed content of Custom Hooks in React: Reusing Logic Across Components. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
