Blog>
Snippets

Functional Components and Reconciliation

Create a functional component that updates its state and show how React reconciles the changes using a Virtual DOM diff.
import React, { useState, useEffect } from 'react';

// Functional component with internal state
const MyComponent = () => {
  // State hook to keep track of count
  const [count, setCount] = useState(0);

  // Effect hook to update document title on state change
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // Dependency array to run effect on count change

  return (
    <div>
      <p>You clicked {count} times</p>
      {/* Button to update state, trigger re-render, and initiate reconciliation */}
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
};

export default MyComponent;
This code defines a functional React component using hooks. It uses `useState` to keep track of a count state and `useEffect` to perform side effects (updating the document title) whenever the count state changes. The component returns a button that, when clicked, increments the count state. React automatically reconciles the changes in the Virtual DOM.