Engineering note · React Js
Custom Hook : Simplify Code with Reusable Logic
The custom hook in React allows to write data-fetching logic once and reuse it across multiple components.
By Farah Jokhio Published
Setting up a reusable data-fetching function to simplify API calls and state management.
State Initialization with useState:
It initializes a data state variable with null as the default value, using React's useState hook. This variable will hold the fetched data.
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
// rest of the logic
}
Fetching Data with useEffect:
The useEffect hook runs whenever the url changes. It performs a fetch request to the specified url, parses the response as JSON, and updates data with the fetched result.
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(setData);
}, [url]);
Returning Data:
Finally, the function returns the data state variable so it can be used directly in any component that calls useFetch.
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(setData);
}, [url]);
return data;
}
Usage
const data = useFetch('https://api.example.com/data');
More engineering notes
Using useMemo for Caching and Optimizing Performance
~~`useMemo`~~ is a React Hook that helps optimize performance by memoizing (caching) the result of a...
Destructuring Props in Functional Components
When you pass any props to any componenet, as in this example passing name and age as props to Profi...