useEffect
to handle and clean up if necessary.useEffect
for different scenarios, like fetching data, setting up subscriptions and cleaning up resoursesStart by creating a basic functional component in React.
const DataFetchingComponent = () => {
return(
<div>
<h1>Data Fetching Component</h1>
</div>
);
};
export default DataFetchingComponent;
You need a state variable to store the data fetched from the API. Use the useState
hook for this.
import {useState} from 'react';
const DataFetchingComponent = () => {
const [data, setData] = useState(null); //Initialize state for storing data
return(
<div>
<h1>Data Fetching Component</h1>
</div>
);
};
export default DataFetchingComponent;
useState(null)
initializes data
with value of null
.setData
is the function you will use to update the data
stateNext use the useEffect
hook to fetch data when component mounts.
import {useState, useEffect} from 'react';
const DataFetchingComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async() =>{
try{
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const result = await response.json();
setData(result);
} catch(error) {
console.error(`Error fetching data: ${error}`);
}
};
fetchData();
},[]); // Empty dependency array to run only once on mount
return(
<div>
<h1>Data Fetching Component</h1>
</div>
)
};
export default DataFetchingComponent;
useEffect(() => {}, [])
runs the code once, when the component mounts. The empty array []
ensures this.fetchData
is an asynchromous function that fetches data from the given API.setData(result)
updates the data
state with the fetched result.Now that the data is fetched and stored in state, render it in your component.
import {useState, useEffect} from 'react';
const DataFetchingComponent = () => {
const [data, setData], useState(null);
useEffect(() => {
const fetchData = async() => {
try{
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const result = await response.json();
setData(result);
}catch(error){
console.error(`Error fetching data: ${error}`);
}
}
fetchData();
}, []);
return(
<div>
<h1>Fetching data example</h1>
{data ? (
<ul>
{data.map((item, idx) => (
<li key={idx}>{item.title}</li>
))}
</ul>
) : (
<p>Loading...</p>
)
}
</div>
);
};
export default DataFetchingComponent;
data ? (...):(...)
: This is a conditional (ternary) operator. If data
is not null
, it renders a list of data; otherwise, it shows a “Loading…” message.data.map((item, idx) => ...)
: Iterates over the fetched data array and renders each item as a list element.In some cases, you might to clean up after side affects. For example, if you set up subscriptions or timers. In this case, no clean up in required because there’s no ongoing subscription or timer.
import {useState, useEffect} from 'react';
const DataFetchingComponent = () => {
const [data, setData], useState(null);
useEffect(() => {
const fetchData = async() => {
try{
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const result = await response.json();
setData(result);
}catch(error){
console.error(`Error fetching data: ${error}`);
}
}
fetchData();
//Cleanup function (not necessary here)
return () =>{
//cleanup logic (e.g., unsubscribe, clear timers, etc.)
}
}, []);
return(
<div>
<h1>Fetching data example</h1>
{data ? (
<ul>
{data.map((item, idx) => (
<li key={idx}>{item.title}</li>
))}
</ul>
) : (
<p>Loading...</p>
)
}
</div>
);
};
export default DataFetchingComponent;
useEffect
: This hook is essential for side effects in functional components, such as data fetching. It can run on mount, on updates, or on unmount depending on the dependency array.useState
: Manages the local state of the component, allowing it to be reactive to changes (e.g., updating the UI when new data is fetched).You can find this example using TypeScrip on my github