Open In App

What are hooks and when we use them ?

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Hooks are features that react provides us if we want to make functional components while creating a react web app. These features are alternatives to a few lifecycle methods like componentDidMount(), componentDidUpdate(), apart from this it gives us more flexibility to write maintainable code.

Prerequisites

Table of Content

  • UseState Hooks
  • UseEffect Hooks
  • UseRef Hooks

1. React useState() hooks: This hook helps functional components to manage state. It takes one argument, the initial state, and returns an array which contains the current state and a function to update that value.

Syntax:

const [state, setState] = useState( );


2. React useEffect() hooks: This hooks helps to perform sideEffect like data fetching, manual DOM manipulations etc. when page is rendered. It serves similar purpose as lifecycle methods in class components (such as componentDidMount, componentDidUpdate, and componentWillUnmount). It accepts two arguments: a function and an optional dependency array.

Syntax:

useEffect(() => {
    console.log("welcome to geeks for geeks");
}, [input])

3. React useRef() hooks: This hook is mainly used to create a reference to the DOM element. It preserves the value across various re-renders and do not cause re-renders whenever a value is changed, make the application faster and helps in caching and storing previous values. It accepts only one initial value and returns an object which has a current property.

Syntax:

const stateRef = useRef();
// some code ...
<input ref={stateRef} type='text' />

Now we will create a weather app with the help of these hooks.

Steps to create React Application

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. function demo, move to it using the following command.

cd foldername

Step 3: Install Axios as a dependency.

npm install axios

Step 4: Run the development server.

npm start

Project structure: 

Example: Now create two files named App.js and WeatherComponent.js

App.js




import "./App.css";
import { useState, useRef } from "react";
import WeatherData from "./Components/WeatherComponent";
 
function App() {
    const [state, setstate] = useState("");
    const inputRef = useRef(null);
 
    const handleClick = () => {
        setstate(inputRef.current);
    };
 
    return (
        <div
            className="App"
            style={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                flexDirection: "column",
                margin: "1rem",
            }}
        >
            <div>
                <input
                    type="text"
                    onChange={(e) => (inputRef.current =
                        e.target.value)}
                    style={{
                        outline: "none",
                        border: "none",
                        borderBottom: "1px solid
                            rgb(110, 204, 113)",
                        margin: ".5rem",
                    }}
                    placeholder="Enter City"
                />
                <button
                    onClick={handleClick}
                    style={{
                        outline: "none",
                        border: "none",
                        backgroundColor:
                            "rgb(110, 204, 113)",
                        padding: "8px",
                        borderRadius: "5px",
                        width: "60px",
                        cursor: "pointer",
                    }}
                >
                    Find
                </button>
            </div>
            <WeatherData location={state} />
        </div>
    );
}
 
export default App;


WeatherComponent.js




import React, { useState, useEffect } from "react";
import axios from "axios";
 
const WeatherComponent = ({ location }) => {
  const [weatherData, setWeatherData] = useState(null);
 
  useEffect(() => {
    const fetchData = async () => {
      if (location === undefined || location === null || location.length === 0)
        location = "Delhi";
 
      var options = {
        method: "GET",
        params: { q: location, days: "2" },
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key":
            "ffc2438edbmsh0a88b634e6e77a7p123125jsnfb163d4d72f7",
        },
      };
      const response = await axios.request(options);
      console.log("response.data", response.data);
      setWeatherData(response.data);
    };
    fetchData();
  }, [location]);
 
  let displayData = "Loading...";
  if (weatherData !== null && weatherData !== undefined) {
    displayData = (
      <div
        style={{
          width: "40vw",
          padding: "15px",
          border: "2px solid rgb(110, 204, 113)",
          borderRadius: "8px",
        }}
      >
        <h3>Weather Info</h3>
        <h4> Region: {weatherData.location.region} </h4>
        <div style={{ display: "flex",
                      justifyContent: "space-between" }}>
          <p style={{ display: "inline" }}>
            Whether:
            {weatherData.forecast.forecastday[0].day.condition.text}
          </p>
 
          <p style={{ display: "inline" }}>
            Date:
            {weatherData.forecast.forecastday[0].date}{" "}
          </p>
 
        </div>
        <div style={{ display: "flex",
                      justifyContent: "space-between" }}>
          <p style={{ display: "inline" }}>
            Whether:
            {weatherData.forecast.forecastday[1].day.condition.text}
          </p>
 
          <p style={{ display: "inline" }}>
            Date:
            {weatherData.forecast.forecastday[1].date}{" "}
          </p>
 
        </div>
      </div>
    );
  }
 
  return <>{displayData}</>;
};
 
export default WeatherComponent;


Output:

a working demo of the app

Explanation:

In this react application we have used the above stated three hooks and their simultaneous working. First, the user will land into the application by default the weather data related to Delhi will be fetched and the state of the WeatherData component will get updated to the object of Delhi’s weather data. If the user enters any city’s name on the input and clicks the button the state of the App component will get updated to the input’s value and will get passed to the WeatherData component as a location prop. Then because of the dependency array, the useEffect’s function will run again and fetch weather data for the specified location thereby updating the state of the WeatherComponent.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads