A Comprehensive Guide: All About ReactJS Hooks for Optimized Development
Unlocking the Power of ReactJS Hooks: A Deep Dive into Essential Concepts
Table of contents
Imagine you're building a magical castle out of building blocks. Each block is like a special tool that helps you create your castle. In the land of programming, React.js is like a magic spell that helps us build amazing things on the computer screen.
Now, in this magical world of React, there are these things called "hooks." Think of them as little helper spells that make it easier to create different parts of your castle. When you use a hook, it's like waving a wand and making something happen. It's like a magic spell from the Harry Potter series, which you spell and it performs a special task.
In ReactJs, they help us to perform some special tasks, and feels like you are performing a magic trick in the world of React. "Hooks let you use different React features from your components. You can either use the built-in Hooks or combine them to build your own.
"
In this Blog, we will dive into the world of Hooks in ReactJs.
UseState
Before starting UseState Hook, you need to understand what is State in ReactJs. You can simply now understand it as a memory in react which keeps track of things when the code is being rendered and while the program is running.
e.g., You created an e-commerce website and when the user adds an item in the cart, it updates a few things, such as the cart has new items, it was empty before, and the item you added/purchased will show that this is added or purchased.
This is what the state does in react, it is like component-specific memory.
In ReactJs UseState is used for this, This hook helps to store the state variable to your component.
const [state, setState] = useState(initialState);
import React, { useState } from 'react';
function MagicButton() {
// Here's the simplest use of useState
// The count variable will store the number of times the button is clicked
// The setCount function will let us update the count
// Count is state variable ans setCount is State Setter function.
const [count, setCount] = useState(0);
// This function will be called when the button is clicked
const handleClick = () => {
setCount(count + 1); // Increasing the count by 1
};
return (
<div>
<p>Number of Clicks: {count}</p>
<button onClick={handleClick}>Click Me!</button>
</div>
);
}
export default MagicButton;
In the above code you can see that count is storing a state variable that is initially zero, when the handleClick() is called, or the button is clicked, the setCount state Setter function will now set the state variable, that is count to count + 1.
So for these types of functions and storing the state variables, use UseState Hook.
UseEffect
Before understanding UseEffect, we need to understand what is Effect. In React, an "Effect" is something you want to do after your component is all setup. Let's take a simpler example:-
Suppose you have a mirror in your room in which the clouds can be seen clearly, and you want that whenever the cloud changes you need to update the mirror and show some data. "Effect" is like an Assistant you have, which when sees that the weather is changing, updates the mirror and keeps you up-to-date about the weather data.
Now UseEffect is the Assistant of the react which observes the changes and updates it. When we use "useEffect" we tell react that, hey react whenever you see this particular change happening, perform this task.
useEffect(() => {
//code to be performed after observing changes
}, []);
import React, { useEffect, useState } from 'react';
function WeatherMirror() {
const [weather, setWeather] = useState('Sunny');
useEffect(() => {
const fetchedWeather = fetchWeatherData();
setWeather(fetchedWeather);
}, []);
return (
<div>
<h1>Magic Weather Mirror</h1>
<p>Current Weather: {weather}</p>
</div>
);
}
export default WeatherMirror;
useEffect(() => {
// This is where you put the code/function you want to happen after rendering
// For our example, let's just pretend we're fetching weather data here
const fetchedWeather = fetchWeatherData();
// Imagine this function fetches weather data
setWeather(fetchedWeather); // Update the weather in our mirror
}, []);
The empty array means this effect runs only once after initial rendering. Suppose we put anything inside the empty array, the effect will run whenever the thing inside the array changes.
useRef
useRef is mainly used in React to connect with things like Buttons, Input Fields or any other component. It is similar to document.getElementById
in vanilla JavaScript. In React, useRef
is a hook that returns a mutable ref object. This object has a current
property that can hold a value that persists across renders without triggering re-renders. This makes it useful for keeping track of values that don't necessarily influence the UI.
Mutable ref Object
useRef
hook. It's an object that can hold different values, and you can update what's inside without triggering re-renders of your React component. This ref object is mutable because you can modify its current
property without affecting the rest of the component's rendering.Below is an example, in this, we want that whenever we click on a button, the input button gets focused.
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null); // This is how we call useRef in React js
const handleButtonClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} /> // Here we passed the ref value
<button onClick={handleButtonClick}>Focus Input</button>
</div>
);
}
export default MyComponent;
We used the current
property of the ref hook and called the focus
function whenever the Button is clicked.
useContext
useContext is one of the most important hooks, but before understanding useContext, we should understand what is context in react. In React, "context" is a way to share data between components without passing it explicitly through props at every level of the component tree. It's especially useful when certain data needs to be accessed by many components throughout an application.
In React, the "useContext" hook is a way to access data or functions that are provided by a higher-level component, without having to pass this data through every intermediate component in the component tree. I found this example on React.dev website The best example that can explain useContext in a better way.
useContext
helps different parts of the app share and use the same theme color, making sure they all match without needing to pass the color around manually. It's like giving all the pages of a coloring book the same crayon color, so they stay in sync. When you change the color with a special switch, all the pages update together, just like how the theme changes for all the parts of the app.
useMemo
useMemo
is a hook in React that helps optimize performance by memorizing (remembering) the result of a function or computation, and only recalculating it when the inputs (dependencies) change. It's useful for avoiding unnecessary and potentially expensive calculations, especially when dealing with complex computations or rendering in components.
In this example below I found the most easy and fun way to understand useMemo and what are the functions it performs and how it works,
useMemo
is like having a magical cookie jar where you keep the cookies you've already baked. When you want more cookies, you first check the jar โ if the cookies are already there and the recipe hasn't changed, you just take them out. But if the recipe ingredients change, you bake new cookies and put them in the jar. This way, you save time by not baking cookies over and over again if you don't need to.import React, { useState, useMemo } from 'react';
function WeatherApp({ weatherCondition }) {
const backgroundClassName = useMemo(() => {
console.log("Calculating background class...");
return weatherCondition === 'sunny' ? 'bg-sunny' : 'bg-cloudy';
}, [weatherCondition]);
return <div className={backgroundClassName}>Today's Weather: {weatherCondition}</div>;
}
Imagine you're building a weather app where you display different backgrounds based on the current weather conditions. Using useMemo
, you can calculate the background class name based on the weather condition and memorize it. This prevents unnecessary re-calculation of the class name during every render, improving performance.