Learn React · 12/13

Advanced Hooks & Performance Optimization

6 min read

Advanced Hooks & Performance Optimization 🚀

Welcome back, intrepid React developer! You've mastered the basics, and now it's time to level up your skills. In this section, we'll dive into some advanced Hooks that will empower you to manage complex state and optimize your application's performance. Think of these as the power tools in your React toolkit. 🛠️


1. useReducer: Managing Complex State Logic 🧠

Definition:
The useReducer hook is an alternative to useState for managing state in your components. It is particularly useful when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

The Problem:
Imagine you're building a component with a state object that has several properties. As the component grows, the logic for updating this state can become scattered and difficult to manage within various event handlers. This can lead to bugs and make the component harder to understand and maintain.

The Solution:
useReducer helps you centralize your state update logic. It takes a "reducer" function and an initial state as arguments and returns the current state and a dispatch function.

How it Works:
Instead of updating the state directly, you dispatch an "action" object. This action is then handled by the reducer function, which takes the current state and the action, and returns the new state.

Let's look at a simple counter example to see it in action:

javascript
import React, { useReducer } from 'react';

const initialState = { count: 0 };

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

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

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

In this example, all the logic for updating the count is neatly contained within the reducer function. The component itself only needs to dispatch the appropriate action.

Industry Practice:
While useState is perfect for simple state, useReducer is often preferred in scenarios with more complex state transitions, like managing form state with multiple fields and validation rules, or when the next state is derived from the previous one.


2. Caching Expensive Calculations with useMemo ⚙️

Definition:
useMemo is a React Hook that memoizes the result of a function call. "Memoization" is a fancy word for caching. useMemo will only re-run the function when one of its dependencies has changed, otherwise it returns the cached result.

The Problem:
Sometimes, you might have a component that performs a computationally expensive calculation on every render. This can slow down your application, especially if the component re-renders frequently for reasons unrelated to the data used in the calculation.

The Solution:
By wrapping the expensive calculation in useMemo, you can ensure that it only runs when absolutely necessary.

How it Works:
useMemo takes a function and an array of dependencies. It will call the function and return its result. On subsequent renders, if the dependencies haven't changed, it will return the cached result without re-executing the function.

Consider a function that calculates the factorial of a number, which can be slow for large numbers:

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

const calculateFactorial = (n) => {
  if (n < 0) return -1;
  if (n === 0) return 1;
  return n * calculateFactorial(n - 1);
};

function FactorialCalculator() {
  const [number, setNumber] = useState(5);
  const [inc, setInc] = useState(0);

  const factorial = useMemo(() => calculateFactorial(number), [number]);

  return (
    <div>
      Factorial of {number} is {factorial}
      <button onClick={() => setNumber(number + 1)}>Increment Number</button>
      <button onClick={() => setInc(inc + 1)}>Re-render</button>
    </div>
  );
}

In this example, clicking the "Re-render" button will not cause the calculateFactorial function to run again because the number dependency has not changed.

Industry Practice:
Use useMemo for calculations that are noticeably slow. Don't wrap every function in useMemo, as this can add unnecessary overhead. It's a tool for optimization, not a default for every calculation.


3. Stabilizing Functions with useCallback 🤝

Definition:
The useCallback hook returns a memoized version of a callback function. This means the function will only be re-created if one of its dependencies changes.

The Problem:
In JavaScript, functions are objects. This means that every time a component re-renders, any functions defined inside it are re-created. This is usually not a problem, but it can lead to unnecessary re-renders of child components that receive these functions as props.

The Solution:
useCallback helps you create stable functions that don't change on every render, unless their dependencies do.

How it Works:
Similar to useMemo, useCallback takes a function and an array of dependencies. It returns a memoized version of the function.

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

const MyButton = React.memo(({ onClick, children }) => {
  console.log('Button rendered');
  return <button onClick={onClick}>{children}</button>;
});

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

  const handleIncrement = useCallback(() => {
    setCount(c => c + 1);
  }, []);

  return (
    <div>
      Count: {count}
      <MyButton onClick={handleIncrement}>Increment</MyButton>
    </div>
  );
}

In this example, because handleIncrement is wrapped in useCallback with an empty dependency array, it will be the same function instance across re-renders. This prevents the MyButton component from re-rendering unnecessarily.

Industry Practice:
useCallback is most beneficial when you are passing callbacks to child components that are optimized with React.memo. It helps prevent breaking the memoization of those child components.


4. React.memo: Preventing Unnecessary Re-renders 🖼️

Definition:
React.memo is a higher-order component (HOC) that memoizes a component. It prevents a component from re-rendering if its props have not changed.

The Problem:
By default, when a parent component re-renders, all of its child components also re-render. This can be inefficient if a child component's output doesn't change because its props are the same.

The Solution:
Wrapping a component in React.memo tells React to skip re-rendering the component if its props are shallowly equal to the props from the previous render.

How it Works:
You simply wrap your functional component with React.memo.

javascript
import React from 'react';

const Greeting = React.memo(({ name }) => {
  console.log('Greeting rendered');
  return <h1>Hello, {name}!</h1>;
});

function App() {
  const [name, setName] = useState('John');
  const [random, setRandom] = useState(0);

  return (
    <div>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <Greeting name={name} />
      <button onClick={() => setRandom(Math.random())}>Re-render App</button>
    </div>
  );
}

In this example, clicking the "Re-render App" button will not cause the Greeting component to re-render because its name prop hasn't changed.

Industry Practice:
React.memo is a great tool for optimizing components that are rendered often with the same props. It's particularly useful for presentational components that receive data and don't have their own internal state.


Extra Reading & References 📚

Challenge

You are tasked with optimizing a React component that displays a list of products. The component is currently inefficient, leading to unnecessary re-renders and slow filtering, especially with a large dataset.

Your goal is to refactor the ProductCatalog and ProductItem components using advanced React Hooks and React.memo to improve performance.

Requirements:

  1. Manage Cart State with useReducer: Convert the cart's state management from useState to useReducer. Implement a cartReducer function that handles two action types: ADD_ITEM and REMOVE_ITEM. The state should be an object with an items array.
  2. Memoize Expensive Computations with useMemo: The product filtering logic is computationally expensive. Wrap the filtering calculation in useMemo so that it only re-runs when the products list or the searchTerm changes.
  3. Memoize the ProductItem Component: The ProductItem component re-renders every time its parent ProductCatalog re-renders. Prevent these unnecessary re-renders by wrapping the ProductItem component export with React.memo.
  4. Stabilize Callback Functions with useCallback: To ensure React.memo on ProductItem works correctly, the handleAddToCart function passed as a prop must have a stable reference. Wrap the handleAddToCart function in the ProductCatalog component with useCallback.

Expected result

Your final code should correctly implement all the specified optimizations.

  1. A cartReducer function exists and is used in a useReducer hook within ProductCatalog to manage the cart state. The reducer must correctly handle ADD_ITEM and REMOVE_ITEM action types.
  2. The filteredProducts variable inside ProductCatalog is calculated using the useMemo hook. Its dependency array must correctly include products and searchTerm.
  3. The handleAddToCart function inside ProductCatalog is wrapped in the useCallback hook. Its dependency array should be correctly configured (it will likely depend on the dispatch function from useReducer).
  4. The ProductItem component is wrapped in React.memo upon export, for example: export const MemoizedProductItem = React.memo(ProductItem); or export default React.memo(ProductItem);.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.