Introduction to Components, Functions and Hooks

Necessary Concepts

This module introduces the core React concepts that power your Weather App. You'll learn how we structure the app using components, manage state with hooks like useState and useEffect, handle user input and events, and fetch real-time weather data from an external API. By the end of this module, you’ll understand exactly how your weather app works under the hood.

Components

In React, components are the heart of your UI. They break your app into reusable, independent pieces. In our weather app, we use both:

  • App.js – the main component that controls overall app logic.
  • WeatherCard.js – a child component that receives weather data via props and displays it with stylized visuals.

Each component is written as a JavaScript function that returns JSX — a syntax that looks like HTML but works inside JavaScript.

Functions & Event Handling

Our app uses arrow functions to keep logic clean and modern. These functions are often attached to event listeners like onClick to respond to user actions.

Here’s how we handle the Search button:

const handleSearch = async () => {
  const data = await getWeatherByCity(city);
  setWeather(data);
};

This function is triggered when a user clicks the “Search” button:

<button onClick={handleSearch}>Search</button>

Event-driven design like this helps React apps stay interactive and responsive. The handleSearch function is responsible for calling our API function, retrieving the weather, and updating the app state.

State & React Hooks

React’s state mechanism allows our app to “remember” information like the city name and the weather data.

We use the useState Hook to create reactive state variables:

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

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

  • city stores the text the user types into the input box.
  • weather stores the response we get from the weather API.

Whenever we call setWeather, React automatically re-renders the component to reflect the new data in the UI. This is the core of React’s reactive design.

Fetching Weather Data from an API

At the heart of our app is real-time weather data. To get it, we use the OpenWeatherMap API and fetch data with a custom service inside WeatherService.js.

const getWeatherByCity = async (city) => {
  const response = await fetch(`${BASE_URL}?q=${city}&appid=${API_KEY}&units=metric`);
  const data = await response.json();
  return data;
};

We use fetch() to make a GET request to the OpenWeatherMap API. The response contains information like temperature, wind, weather type, and more — which we pass to the WeatherCard to display beautifully. This setup ensures your app updates in real-time when a user searches for any city!