What are hooks and when we use them ?
Last Updated :
25 Jul, 2024
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",
url: "https://weatherapi-com.p.rapidapi.com/forecast.json",
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:
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.
Similar Reads
What's the concept of custom hooks, and why do we use them? Custom hooks in React are JavaScript functions that utilize built-in React hooks or other custom hooks to encapsulate reusable logic in functional components. They follow a naming convention where the function name starts with "use" (e.g., useCustomHook). Custom hooks allow users to abstract complex
3 min read
What are React Hooks, and why were they added to React? React Hooks are a way to add functionality to functional components in React. Before Hooks, functional components were more limited compared to class components in terms of what they could do. With Hooks, users can now use state, lifecycle methods, and other React features in functional components,
2 min read
What Are Plugins and How Do They Work? Welcome to our article about what are Plugins and how do they work! Have you ever wondered how your favorite apps and websites get extra features? That's where plugins come in! Plugins are like small add-ons that make software or websites better. They work by joining with the main software or websit
8 min read
What are the rules of hooks in React, and why are they important? In React, hooks empower functional components to utilize state and incorporate other React functionalities seamlessly, enabling a more dynamic and concise development approach. Rules of Hooks in React:Only use hooks at the top level: This means don't use hooks inside loops, conditions, or nested fun
2 min read
When should we use the useEffect hook? The useEffect hook in React is used to perform side effects in functional components. Side effects are actions that happen outside of the normal flow of the component, such as fetching data from an API, subscribing to events, or updating the DOM. When should we use the useEffect hook?Data Fetching:I
2 min read