React Hooks

What Are React Hooks?

React Hooks are tools (functions) in React. It is allows you to add features like state, effects and shared logic to functional components.

For Example: you can see an “Add To Cart” button in online shopping Apps.

  • When a user click the “Add To Cart” button.
  • So it is showing “total items in cart” on your screen and that number will increases with each click.
  • Before Hooks you had to create a class component and write lifecycle methods.
  • But now, with hooks you can easily count Cart numbers with useState Hook in functional component.

Different Types Of React Hooks

Total 15 Hooks are available in react. In this section we will learn all types of hooks of react.

Basic Hooks (introduced in React 16.8)

  1. useState
  2. useEffect
  3. useContext

Additional Hooks

  1. useReducer
  2. useCallback
  3. useMemo
  4. useRef
  5. useImperativeHandle
  6. useLayoutEffect
  7. useDebugValue

Newer Hooks (React 18+)

  1. useId
  2. useTransition
  3. useDeferredValue
  4. useSyncExternalStore
  5. useInsertionEffect

Why Use React Hooks?

Hooks bring several advantages to React development:

  1. Simple Code: Don’t need to write complex class code, your code become shorter and easy to understand with Hooks.
  2. Reusable Logic: No need to write same code again and again. if you have some logic code (like fetching data), so you can put that code in custom hook and reuse in many places.
  3. Enhanced Performance: Hooks reduce unnecessary updates and reloading of components. this reason React apps can run faster and smoother.
  4. Reduced Boilerplate: Hooks handle everything with less code, you don’t need to write extra code like constructors, this keyword and lifecycle methods.

Basic Hooks In React

These all Hooks are introduced in React 16.8. useState, useEffect and useContext are basic hooks in react that are manage component.

We have Covered:

  • useState Hook with proper explanation and live examples, > Learn useState.
  • useContext Hook with proper explanation and live examples > Learn useContext.

1) React useEffect Hook

When some component runs on the screen, useEffect run some code automatically like loading data or checking data. all the code that runs in the background is handled by useEffect.

Let’s Understand Real Life Example : Suppose you are using one Chat App for messaging. whenever any user open the app so it should showing online and offline status.

You are use useState to create one state to showing user are online or offline?

When user is online so it shows true and if user goes offline so it shows false.

Now useEffect use in this case:

When the App are opened so app’s logic use browser system to check user are online or not?

If user internet connection are off so it will shown a offline and if internet are turned on so it shown a online status.

The online and offline status changed by useEffect. the status are automatically change when we load the app, so this automatically code run by useEffect hook in react.

✅ UseEffect Syntax

import { useEffect } from 'react';

useEffect(() => {
// Code you want to run after the component renders
}, [dependencies]);
  • When the component shown on the screen, React runs the function inside useEffect.
  • The [dependencies] list tells React when to run that function again.

💡 Real-Life Example: Show Online/Offline Status

import React, { useState, useEffect } from 'react';

function NetStatusTracker() {
const [connectionStatus, setConnectionStatus] = useState(navigator.onLine);

useEffect(() => {
function handleNetworkChange() {
setConnectionStatus(navigator.onLine);
}

window.addEventListener('online', handleNetworkChange);
window.addEventListener('offline', handleNetworkChange);

// Cleanup function to remove listeners
return () => {
window.removeEventListener('online', handleNetworkChange);
window.removeEventListener('offline', handleNetworkChange);
};
}, []);

return (
<div>
<h2>Network Status: {connectionStatus ? 'Connected ✅' : 'Disconnected ❌'}</h2>
</div>
);
}

export default NetStatusTracker;

In this Code:

  • navigator.onLine checks if the user are online or not.
  • the useEffect runs when the component shown on the screen.
  • it is add a listeners to track online and offline status.
  • the status update automatically, when the user goes offline or comes back online.

Additional Hooks In React

1) useReducer Hook

useReducer Hook used to manage more complex state logic in your app. useReducer works like a small version of Redux inside component.

Why use useReducer Hook In React?

When your state has multiple values, depends on previous state and complex update logic (like switch-case), So you can use useReducer hook instead of useState.

🛒 For Example: Cart Management in Shopping App

Imagine you creating a shopping Cart feature in your app. Cart will handle following types of scenario:

  • ➕ Add item to cart
  • ➖ Remove item from cart
  • 🔄 Reset/empty the cart
  • ✏️ Update item quantity

In this feature If you can use useState so:

  • you are manage array of items.
  • write multiple setState calls for each action.
  • updating quantity needs map/filter logic each time.

It become difficult to manage state but if you are using useReducer:

Create only single function (reducer) to manage all cart changes.

Use simple logic method:

dispatch({ type: 'ADD_ITEM', payload: item })
dispatch({ type: 'REMOVE_ITEM', payload: itemId })
dispatch({ type: 'CLEAR_CART' })
  • It keep your code clean and easy to understand.
  • useState use when your state is simple like one or two values.
  • useReducer use when your state needs multiple actions and updates.

🍔 Food Cart App using useReducer

import React, { useReducer } from 'react';

// Step 1: Initial cart is empty
const initialCart = [];

// Step 2: Define a reducer function to manage cart actions
function cartManager(cartItems, action) {
switch (action.type) {
case 'ADD_FOOD':
return [...cartItems, action.food];
case 'REMOVE_FOOD':
return cartItems.filter((item, index) => index !== action.index);
case 'CLEAR_CART':
return [];
default:
return cartItems;
}
}

function FoodCart() {
// Step 3: useReducer returns current state and dispatch function
const [cart, handleCart] = useReducer(cartManager, initialCart);

return (
<div>
<h2>🍕 Food Menu</h2>
<button onClick={() => handleCart({ type: 'ADD_FOOD', food: 'Burger' })}>
Add Burger
</button>
<button onClick={() => handleCart({ type: 'ADD_FOOD', food: 'Pizza' })}>
Add Pizza
</button>
<button onClick={() => handleCart({ type: 'ADD_FOOD', food: 'Fries' })}>
Add Fries
</button>
<button onClick={() => handleCart({ type: 'CLEAR_CART' })}>
Clear Cart
</button>

<h3>🛒 Your Cart</h3>
<ul>
{cart.map((item, i) => (
<li key={i}>
{item}{' '}
<button onClick={() => handleCart({ type: 'REMOVE_FOOD', index: i })}>
❌ Remove
</button>
</li>
))}
</ul>
</div>
);
}

export default FoodCart;
  • useReducer manage a Cart.
  • When you click on “Add Item,” it add an item to the cart.
  • When you click “Remove,” it removes that specific item.
  • The reducer function checks the type of action and updates the cart.

📚 Real-Life Situation: Student’s Book List App To Add/Remove Books

import React, { useReducer } from 'react';

// Step 1: Starting list is empty
const initialBooks = [];

// Step 2: Book reducer function to handle actions
function bookHandler(currentList, action) {
switch (action.type) {
case 'ADD_BOOK':
return [...currentList, action.book];
case 'REMOVE_BOOK':
return currentList.filter((_, i) => i !== action.index);
default:
return currentList;
}
}

function BookList() {
const [books, updateList] = useReducer(bookHandler, initialBooks);

return (
<div>
<h2>📚 Student Reading List</h2>

<button onClick={() => updateList({ type: 'ADD_BOOK', book: 'React Basics' })}>
➕ Add React Basics
</button>

<button onClick={() => updateList({ type: 'ADD_BOOK', book: 'JavaScript Guide' })}>
➕ Add JavaScript Guide
</button>

<h3>📖 Books You Added:</h3>
<ul>
{books.map((book, i) => (
<li key={i}>
{book}{' '}
<button onClick={() => updateList({ type: 'REMOVE_BOOK', index: i })}>
❌ Remove
</button>
</li>
))}
</ul>
</div>
);
}

export default BookList;
  • Books lists handled by useReducer.
  • When you click on book button, it add that book to the list.
  • You can remove any book by clicking the cross(❌) icon.
  • The reducer decide what to do? (add or remove).

Leave a Comment

BoxofLearn