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.).
Custom hooks provide several benefits:
To create a custom hook, follow these steps:
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;
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;
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;
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;
Custom hooks follow the same rules as React hooks:
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;
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;
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!