Both useEffect and useLayoutEffect are hooks provided by React for managing side effects in functional components. While they are similar in many ways, there are important differences in when they are executed relative to the render cycle. Here's a breakdown of the differences:

Timing of Execution

Scheduling

Performance Considerations

Here's an example to illustrate the usage of both hooks.

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

const MyComponent = () => {
  const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight });

  // useEffect example
  useEffect(() => {
    const handleResize = () => {
      setSize({ width: window.innerWidth, height: window.innerHeight });
    };
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // Run only on mount and unmount

  // useLayoutEffect example
  useLayoutEffect(() => {
    document.title = `Width: ${size.width}, Height: ${size.height}`;
  }, [size]); // Run whenever size changes

  return (
    <div>
      <p>Window Width: {size.width}</p>
      <p>Window Height: {size.height}</p>
    </div>
  );
};

export default MyComponent;

In this example