#20 React Js Challenge Day 20 | React Custom Hooks For Api Calls
Today we will be discussing how to use custom hooks in React for making API calls. Custom hooks are a powerful feature in React that allow us to extract logic and reuse it across multiple components.
What are custom hooks?
Custom hooks are JavaScript functions that use the ‘use’ prefix and can call other hooks if needed. They are a way to extract reusable logic from a component and share it between different components. This allows us to keep our code DRY (Don’t Repeat Yourself) and improve code maintainability.
Using custom hooks for API calls
Let’s say we have a component that needs to make an API call to fetch some data. Instead of writing the code for the API call directly in the component, we can create a custom hook to handle the API call logic.
Here’s an example of a custom hook for making API calls:
import { useState, useEffect } from 'react';
const useApi = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
};
fetchData();
}, [url]);
return { data, loading };
};
export default useApi;
In the above example, we created a custom hook called ‘useApi’ that takes the API URL as a parameter. Inside the hook, we use the ‘useState’ and ‘useEffect’ hooks to manage the state and perform the API call. The hook returns the data and loading state, which can then be used in any component that needs to make an API call.
Using the custom hook in a component
Now that we have our custom hook for API calls, we can use it in a component. Here’s an example of how we can use the ‘useApi’ custom hook to fetch and display data:
import React from 'react';
import useApi from './useApi';
const App = () => {
const {data, loading} = useApi('https://api.example.com/data');
if (loading) {
return Loading...
;
}
return (
{data.map(item => (
{item.name}
))}
);
};
export default App;
In the above example, we import the ‘useApi’ custom hook and use it in the ‘App’ component to fetch and display the data. The ‘data’ and ‘loading’ state returned by the custom hook is used to conditionally render the content based on the API call status.
Conclusion
Custom hooks are a powerful feature in React that allow us to extract and reuse logic across different components. Using custom hooks for API calls can help us keep our code organized and maintainable. By creating a custom hook for API calls, we can easily reuse the logic across different components and make our code more readable and DRY.