React Weather App

Introduction

A Weather App is one of the most popular beginner-to-intermediate React projects.

Modern applications often display real-time data from APIs, and a Weather App is a perfect example of this concept.

In a Weather App, users can:

  • Search for cities
  • Check current temperature
  • View weather conditions
  • See humidity and wind speed
  • Get real-time weather updates

Building a Weather App in React helps developers understand how frontend applications communicate with external APIs.

In this tutorial, you will learn how to create a complete Weather App in React step by step.

What is a Weather App?

A Weather App is a web application that fetches weather information from a weather API and displays it to users.

Technologies Used

We will use:

  • ReactJS
  • useState Hook
  • useEffect Hook
  • Fetch API or Axios
  • OpenWeather API

Setting Up React Project

Create a React app using Vite.

Create Project


npm create vite@latest

Install Dependencies


npm install

Run Development Server


npm run dev

Project Structure


src/
├── App.jsx
├── App.css

Getting Weather API Key

We need a weather API.

Popular weather APIs:

  • OpenWeather API
  • WeatherAPI
  • AccuWeather API

OpenWeather API

Create an account and generate API key.

Example API URL:


https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY

Understanding Weather App Flow

Step 1

User enters city name.

Step 2

React sends API request.

Step 3

Weather API returns data.

Step 4

React updates the UI dynamically.

Creating a Basic Weather App

App.jsx


import { useState } from "react";
function App() {
 const [city, setCity] = useState("");
 const [weather, setWeather] = useState(null);
 const API_KEY =
   "YOUR_API_KEY";
 const getWeather = async () => {
   const response = await fetch(
     `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`
   );
   const data =
     await response.json();
   setWeather(data);
 };
 return (
   <div>
     <h1>Weather App</h1>
     <input
       type="text"
       placeholder="Enter city"
       value={city}
       onChange={(e) =>
         setCity(e.target.value)
       }
     />
     <button onClick={getWeather}>
       Search
     </button>
     {weather && (
       <div>
         <h2>{weather.name}</h2>
         <h3>
           {weather.main.temp}°C
         </h3>
         <p>
           {weather.weather[0].main}
         </p>
       </div>
     )}
   </div>
 );
}
export default App;

Understanding useState in Weather App

We use two states.

City State


const [city, setCity] = useState("");

Stores user input.

Weather State


const [weather, setWeather] = useState(null);

Stores API response data.

How Fetch API Works?

The Fetch API sends HTTP requests.

Example


const response = await fetch(url);

Converting Response into JSON


const data = await response.json();

How Search Function Works?

Step 1

User enters city.

Step 2

Button click triggers getWeather().

Step 3

Fetch API sends request.

Step 4

Weather data returns.

Step 5

State updates.

Step 6

React re-renders UI.

Conditional Rendering

We only display weather data when available.

Example


{weather && (
 <div>

 </div>
)}

Why Conditional Rendering is Important?

Without it:

  • App may crash
  • Undefined errors may occur

Displaying More Weather Information

We can also display:

  • Humidity
  • Wind speed
  • Country
  • Feels like temperature

Example


<p>
 Humidity:
 {weather.main.humidity}%
</p>
<p>
 Wind:
 {weather.wind.speed} km/h
</p>

Adding Loading State

Loading improves user experience.

Add Loading State


const [loading, setLoading] = useState(false);

Update Function


const getWeather = async () => {
 setLoading(true);
 const response = await fetch(url);
 const data = await response.json();
 setWeather(data);
 setLoading(false);
};

Show Loading Message


{loading && <p>Loading...</p>}

Adding Error Handling

Error handling is important.

Example


try {
 const response = await fetch(url);
} catch (error) {
 console.log(error);
}

Complete Error Handling Example


const [error, setError] =
 useState("");
try {
 const response = await fetch(url);
 const data = await response.json();
 if (data.cod === "404") {
   setError("City not found");
 }
} catch (error) {
 setError("Something went wrong");
}

Styling the Weather App

App.css


body {
 font-family: Arial;
 text-align: center;
 background: #f2f2f2;
}
input {
 padding: 10px;
 width: 250px;
}
button {
 padding: 10px;
 margin-left: 10px;
 cursor: pointer;
}

Weather API Response Structure

Example API response:


{
 "name": "London",
 "main": {
   "temp": 18,
   "humidity": 70
 },
 "wind": {
   "speed": 5
 }
}

Accessing Nested Data


weather.main.temp

Real-Life Use Cases of Weather Apps

Weather apps are used in:

  • Travel websites
  • Airline apps
  • Agriculture systems
  • Mobile applications
  • Smart devices

Using Axios Instead of Fetch API

Axios is another popular method.

Install Axios


npm install axios

Axios Example


import axios from "axios";
const response =
 await axios.get(url);
setWeather(response.data);

Fetch API vs Axios

Feature Fetch API Axios
Built into JavaScript Yes No
JSON Conversion Manual Automatic
Error Handling Basic Better
External Package No Yes

Common Mistakes While Building Weather App

1. Forgetting API Key

Wrong API key causes errors.

2. Not Handling Undefined Data

Wrong:


weather.main.temp

before data loads.

3. Missing Error Handling

Always handle:

  • Network errors
  • Invalid city names

4. Not Using Conditional Rendering

This may crash the application.

5. Exposing API Key Publicly

Use environment variables.

Using Environment Variables

Store API key securely.

Example


VITE_API_KEY=your_api_key

Accessing Environment Variable


import.meta.env.VITE_API_KEY

Improving Weather App

You can improve app using:

  • Weather icons
  • Dark mode
  • 5-day forecast
  • Geolocation
  • Search history
  • Responsive design

Advanced Weather App Ideas

Advanced features:

  • Hourly forecast
  • Animated backgrounds
  • Voice search
  • Multiple city tracking
  • Air quality index

Weather App with useEffect

Automatically fetch default city weather.

Example


useEffect(() => {
 getWeather();
}, []);

Why Weather App is Important for React Learning?

Weather App teaches:

  • API communication
  • React Hooks
  • Async operations
  • Error handling
  • Conditional rendering

It is one of the best intermediate React projects.

Best Practices

1. Handle Loading State

Improves user experience.

2. Handle Errors Properly

Prevent crashes.

3. Use Environment Variables

Protect API keys.

4. Use Reusable Components

Create:

  • SearchBar
  • WeatherCard
  • Loader

5. Optimize API Requests

Avoid unnecessary API calls.

Conclusion

A Weather App is one of the best React projects for learning API integration and real-world frontend development.

Building projects like Weather Apps improves:

  • React fundamentals
  • API handling skills
  • Problem-solving abilities
  • Frontend development confidence

Continue Learning React