Taming Side Effects in React with useEffect and useState
React is a powerful JavaScript library for building user interfaces. One of its key features is the ability to manage component state through hooks, like useState and useEffect. In this blog post, we will explore a cool and useful example of how to use useEffect in conjunction with useState to manage side effects in your React applications.
The Problem
Imagine you are building a simple weather application that fetches the current temperature for a given city. To build this app, we need to make API calls to a weather service, update the component state with the fetched data, and handle any errors that might occur. This is a perfect use case for the useEffect and useState hooks.
Setting Up useState
First, let’s set up the component state using the useState hook. We need to track the city, temperature, and any errors that might occur during the API call. Here’s how to initialize the state:
import React, { useState, useEffect } from 'react';
function WeatherApp() {
const [city, setCity] = useState('');
const [temperature, setTemperature] = useState(null);
const [error, setError] = useState(null);
// ... rest of the component
}
Integrating useEffect
Now that we have our state set up, let’s use the useEffect hook to fetch the temperature for the specified city when the city value changes. We’ll use the popular fetch
function to make the API call to api.weatherapi.com to get the weather in a particular city:
import React, { useState, useEffect } from 'react';
function WeatherApp() {
// function that fetches the temperature from the weatherapi.com api
const fetchTemperature = async () => {
try {
const response = await fetch(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`);
const data = await response.json();
if (response.ok) {
setTemperature(data.current.temp_c);
setError(null);
} else {
setError(data.error.message);
}
}
catch (error) {
setError('An error occurred while fetching the temperature.');
}
};
const [city, setCity] = useState('');
const [temperature, setTemperature] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
if (city) {
fetchTemperature();
}
}, [city]);
// ... rest of the component
}
In this example, useEffect takes two arguments:
- A function that runs the side effect (fetching the temperature)
- An array of dependencies, in this case
[city]
, which means the effect will only run when the city value changes.
Handling User Input and Rendering
Finally, let’s handle user input and render the fetched temperature or any errors that might occur:
import React, { useState, useEffect } from 'react';
function WeatherApp() {
// ... useState and useEffect declarations
const handleCityChange = (event) => {
setCity(event.target.value);
};
return (
<div>
<input type="text" value={city} onChange={handleCityChange} placeholder="Enter a city" />
{temperature && <p>Current temperature: {temperature}°C</p>}
{error && <p>Error: {error}</p>}
</div>
);
}
export default WeatherApp;
Conclusion
In this blog post, we’ve demonstrated a fun example of using useEffect and useState to fetch and display weather data in a React application. This example showcased the power of hooks in managing component state and side effects, making it easier to create efficient and maintainable code.
Leave a Reply