Member-only story
How to Build a Custom Hooks to Fetch API in React
to make your code more clean and readable
3 min readAug 24, 2024
Usually when you call an api in react, you will often see code something like this:
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch('/api/posts');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result);
} finally {
setLoading(false);
}
};
fetchData();
}, []); // Empty dependency array means this effect runs once on mount
This is fine, but we can use Custom Hooks to make code more readable and look clean like code below:
const { data, isLoading } = useFetch();
Preview:
So, this time we will try to create API post with fake data and call the API using Custom Hooks, lets start.
Prerequisite:
- Next App Router