Home >Web Front-end >JS Tutorial >Understanding and Creating Custom Hooks in React
Ensure you have the necessary background knowledge in these:
Basic Knowledge of React
Node.js and npm
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.
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.
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:
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.
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: let create a simple counter App with React hook(useState).in app.jsx
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.
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;
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;
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;
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;
One of the main benefits is reusability. You can use the same custom hook in multiple components, reducing code duplication.
Custom hooks help you separate the logic from the UI. Your components focus on rendering, while the custom hooks handle the logic.
By moving complex logic to custom hooks, your components become simpler and easier to understand.
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.
When using hooks like useEffect inside a custom hook, make sure to handle dependencies correctly to avoid bugs or 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.
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!