DeveloperBreeze

React Cheatsheet Development Tutorials, Guides & Insights

Unlock 1+ expert-curated react cheatsheet tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your react cheatsheet skills on DeveloperBreeze.

React Performance Optimization Cheatsheet: Hooks, Memoization, and Lazy Loading

Cheatsheet August 20, 2024
javascript

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

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

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    <div>
      <ChildComponent onClick={increment} />
      <p>Count: {count}</p>
    </div>
  );
}

function ChildComponent({ onClick }) {
  console.log('Child component re-rendered');
  return <button onClick={onClick}>Increment</button>;
}

Here, useCallback prevents the increment function from being recreated on every render, which in turn prevents the ChildComponent from unnecessary re-renders.