React Counter Component

Counter button using useState hook

import { useState } from 'react';

const CounterButton = () => {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <button onClick={handleClick}>
      Clicked {count} times
    </button>
  );
}

const MyApp = () => {
  return (
    <div>
      <h1>Counters that update separately</h1>
      <CounterButton />
      <CounterButton />
    </div>
  );
}

Counter button with sharing state (moving state to the parent component)

import { useState } from 'react';

const CounterButtonSharedState = (props: { count: number; onClick: () => void }) => {
    return (
      <button onClick={props.onClick}>
        Clicked {props.count} times (connected)
      </button>
    );
};

const MyApp = () => {
  const [count, setCount] = useState(0);

  function handleCounterClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <h1>Counters that update together</h1>
      <CounterButtonSharedState count={count} onClick={handleCounterClick} />
      <CounterButtonSharedState count={count} onClick={handleCounterClick} />
    </div>
  );
}

Leave a Comment