📅  最后修改于: 2023-12-03 15:19:44.760000             🧑  作者: Mango
A custom hook is a function that uses React's useState
, useEffect
, and other hooks to create a reusable logic. This can help simplify your code and make it more readable by separating concerns.
In this guide, we will create a custom hook using TypeScript. TypeScript adds static typing and interfaces to our code, which helps us write more robust and type-safe applications.
We will build a custom hook that fetches data from an API and handles loading and error states. This hook will be reusable and easy to use in any component.
To create our custom hook, we will use the useEffect
and useState
hooks provided by React. First, we need to define the shape of our data by creating an interface for our API response:
interface Data {
id: number;
name: string;
email: string;
}
Next, we can define our custom hook function:
import { useState, useEffect } from 'react';
function useFetchData(url: string) {
const [data, setData] = useState<Data | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const json = await response.json();
setData(json);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
}
fetchData();
}, [url]);
return { data, loading, error };
}
In this code, we define three states using useState
: data
, loading
, and error
. We then use useEffect
to fetch data from the API, set the state with the response, and handle any errors. Finally, we return an object with the three states.
Now that our custom hook is complete, we can use it in any React component. We simply call the hook with the API URL and destructure the returned object:
function MyComponent() {
const { data, loading, error } = useFetchData('https://jsonplaceholder.typicode.com/users/1');
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return (
<div>
<h1>{data?.name}</h1>
<p>{data?.email}</p>
</div>
);
}
In this code, we render a loading spinner while the data is being fetched. If an error occurs, we display the error message. Finally, we render the data once it has been fetched.
Custom hooks are powerful tools that can help simplify your code and make it more readable. By combining TypeScript and React, we can create custom hooks that are type-safe and easy to use in any component.