Skip to main content

Additional React Hooks – Advanced State and Performance Optimizations

Advanced React Hooks: useReducer, useCallback, and useMemo

Advanced React Hooks: useReducer, useCallback, and useMemo

In this blog, we will explore advanced React hooks that allow you to handle complex state logic, optimize performance, and manage expensive calculations.

1. useReducer

What is it? useReducer is similar to useState, but it’s better suited for complex state logic, like when there are multiple state transitions or actions.

Real-Life Example: Imagine a simple counter with multiple actions: increment, decrement, and reset.


import React, { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return { count: 0 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  );
}

    

2. useCallback

What is it? useCallback is used to memoize functions, preventing unnecessary re-creations of functions on each render.

Real-Life Example: In large applications, you may pass functions as props to child components. If the function is recreated on every render, it can hurt performance.


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

function ParentComponent() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

  return (
    <div>
      <button onClick={handleClick}>Click me</button>
      <p>Count: {count}</p>
    </div>
  );
}

    

3. useMemo

What is it? useMemo memoizes expensive calculations, preventing them from being recalculated on every render.

Real-Life Example: If you have a component that performs a heavy calculation, useMemo ensures the result is only recalculated when necessary.


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

function ExpensiveCalculation() {
  const [number, setNumber] = useState(0);
  const [dark, setDark] = useState(false);

  const theme = useMemo(() => {
    return { background: dark ? 'black' : 'white', color: dark ? 'white' : 'black' };
  }, [dark]);

  return (
    <div style={theme}>
      <input type="number" value={number} onChange={e => setNumber(parseInt(e.target.value))} />
      <button onClick={() => setDark(prevDark => !prevDark)}>Toggle Theme</button>
    </div>
  );
}

    

These hooks help optimize your app’s performance and make state management easier. Let’s move on to managing refs and layout with the next blog!

Comments

Popular posts from this blog

DevOps Best Practices

 # DevOps Best Practices: Your Ultimate Guide to Modern Software Development In today's fast-paced tech world, DevOps isn't just a buzzword – it's a game-changer. Let's dive into the essential practices that can transform your software development process. ![DevOps Lifecycle](https://blogger.googleusercontent.com/img/placeholder.png) ## 🔄 1. Continuous Integration (CI) - The Foundation Think of CI as your code's quality guardian. Every time developers push code, automated tests run to catch issues early. Here's what makes great CI: - Automated builds triggered with every commit - Comprehensive test suites running automatically - Code quality checks integrated into the pipeline - Quick feedback loops to developers **Pro Tip:** Start with simple automated tests and gradually build up your test suite. Remember, it's better to have a few reliable tests than many unreliable ones. ## 🚀 2. Continuous Delivery (CD) - From Code to Customer CD ensures your software ...

Introduction to Cloud Computing: Revolutionizing the Digital Landscape

In today's rapidly evolving digital world, cloud computing stands as a cornerstone of modern technology, transforming how businesses operate and individuals interact with data. Let's dive deep into this fascinating technology that powers our digital future. ## What is Cloud Computing? Imagine having a virtual supercomputer at your fingertips, accessible from anywhere in the world. That's the essence of cloud computing – a technology that delivers computing services such as storage, databases, software, and processing power over the internet, eliminating the need for physical hardware investments. ## The Three Pillars of Cloud Service Models ### Infrastructure as a Service (IaaS) Think of IaaS as renting the digital building blocks of computing. Companies like Amazon Web Services (AWS) and Microsoft Azure provide virtual machines, storage, and networking resources on-demand. This model offers unprecedented flexibility, allowing businesses to scale their infrastructure up or ...

How to Convert a Next.js Website into a PWA and TWA

🚀 Complete Guide: Converting Next.js to PWA & TWA Transform your Next.js website into a Progressive Web App and wrap it as an Android application using Trusted Web Activity. Every step explained in detail! 📋 Table of Contents What is a PWA? What is a TWA? Prerequisites & Setup Step 1: Convert Next.js to PWA Install Dependencies Configure next.config.js Create Web App Manifest Prepare App Icons Update Document Head Build and Test PWA Step 2: Wrap PWA as TWA Create Asset Links File Install Bubblewrap CLI ...