2024-06-18

React hooks

 

useMemo

useMemo is a hook that memoizes the result of a function, caching its return value to optimize performance. It recalculates the memoized value only when one of its dependencies has changed.

Use Cases

  • Performance Optimization: When you have expensive calculations that you don’t want to run on every render.
  • Pure Functions: Memoize the results of pure functions that return the same output for the same inputs.

Syntax

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Example

import React, { useMemo, useState } from 'react'; const ExampleComponent = () => { const [count, setCount] = useState(0); const [text, setText] = useState(''); const expensiveComputation = (num) => { console.log('Running expensive computation...'); return num * 2; }; const memoizedResult = useMemo(() => expensiveComputation(count), [count]); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> <h2>Memoized Result: {memoizedResult}</h2> <input type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="Type something..." /> </div> ); }; export default ExampleComponent;

In this example, expensiveComputation will only run when count changes, not when text changes.

useEffect

useEffect is a hook that allows you to perform side effects in function components. It runs after the render and can run again when its dependencies change.

Use Cases

  • Data Fetching: Fetching data from an API when the component mounts.
  • Subscriptions: Setting up and cleaning up subscriptions.
  • DOM Manipulations: Directly manipulating the DOM after render.
  • Side Effects: Any other side effects that are not pure computations, such as logging.

Syntax

useEffect(() => { // Effect logic return () => { // Cleanup logic (optional) }; }, [dependencies]);

Example

import React, { useEffect, useState } from 'react'; const ExampleComponent = () => { const [count, setCount] = useState(0); useEffect(() => { console.log('Component mounted or count changed'); return () => { console.log('Cleanup if count changes or component unmounts'); }; }, [count]); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }; export default ExampleComponent;

In this example, the effect runs when the component mounts and whenever count changes. The cleanup function runs before the effect runs next time and when the component unmounts.


useCallback

useCallback is a hook that returns a memoized version of the callback function that only changes if one of its dependencies has changed. It's particularly useful to avoid unnecessary re-renders by preventing functions from being recreated on every render.

Use Cases

  • Passing Callbacks to Child Components: When you pass a callback to a child component that depends on props or state, using useCallback ensures that the function reference remains the same unless dependencies change.
  • Optimizing Performance: It can be used to optimize performance in scenarios where functions are recreated unnecessarily, causing unwanted renders.

Syntax

const memoizedCallback = useCallback(() => { // Callback logic }, [dependencies]);

Example

import React, { useState, useCallback } from 'react'; const ChildComponent = React.memo(({ onClick }) => { console.log('ChildComponent rendered'); return <button onClick={onClick}>Click me</button>; }); const ExampleComponent = () => { const [count, setCount] = useState(0); const [text, setText] = useState(''); const handleClick = useCallback(() => { console.log('Button clicked'); }, []); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> <input type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="Type something..." /> <ChildComponent onClick={handleClick} /> </div> ); }; export default ExampleComponent;

In this example, handleClick will only be recreated if its dependencies change. This prevents ChildComponent from re-rendering unnecessarily.

Key Differences

  1. Purpose:

    • useMemo: Memoizes a value to optimize performance.
    • useCallback: Memoizes a function to avoid unnecessary re-renders.
    • useEffect: Manages side effects in a component.
  2. Timing:

    • useMemo: Runs during render.
    • useCallback: Runs during render, but memoizes the function reference.
    • useEffect: Runs after the render.
  3. Usage:

    • useMemo: Use when you have an expensive calculation that should not re-run on every render unless dependencies change.
    • useCallback: Use when you have a function that you don't want to be recreated on every render unless dependencies change.
    • useEffect: Use for side effects like data fetching, subscriptions, or any code that should run after the component has rendered.

When to Use Each

  • Use useMemo when you have computationally expensive operations and you want to memoize the result to avoid re-computation on every render.
  • Use useEffect when you need to perform side effects such as data fetching, updating the DOM, or subscribing to services.
  • Use useCallback when you need to memoize a function to prevent it from being recreated unnecessarily, especially when passing it as a prop to child components.

By understanding the distinct roles of these hooks and applying them appropriately, you can optimize your React applications for both performance and functionality

No comments: