← React & TypeScript

Coding challenge

create a <Contador /> component that:

Challenge: create a <Contador /> component that:
- Displays the current count value.
- Has buttons to increment, decrement, and reset.
- Accepts an optional prop `inicial` (a number, defaults to 0).

Tests: contador.test.tsx — try to solve it before reading the solution below.
Show solution
// Reto: crea un componente <Contador /> que:
// - Muestre el valor actual de la cuenta.
// - Tenga botones para incrementar, decrementar y reiniciar.
// - Acepte una prop opcional `inicial` (número, por defecto 0).
//
// Tests: contador.test.tsx — intenta resolverlo antes de leer la solución de abajo.

import { useState } from "react";

// Tipamos las props con un type. El "?" hace la prop opcional,
// y el valor por defecto se asigna al destructurar.
type ContadorProps = {
  inicial?: number;
};

export function Contador({ inicial = 0 }: ContadorProps) {
  const [cuenta, setCuenta] = useState(inicial);

  return (
    <div>
      <p>Cuenta: {cuenta}</p>
      {/* Usamos la forma funcional (c => c + 1) porque el nuevo valor
          depende del anterior. Así evitamos bugs si React agrupa updates. */}
      <button onClick={() => setCuenta((c) => c + 1)}>Incrementar</button>
      <button onClick={() => setCuenta((c) => c - 1)}>Decrementar</button>
      {/* Reiniciar no depende del valor anterior: aquí sí pasamos el valor directo. */}
      <button onClick={() => setCuenta(inicial)}>Reiniciar</button>
    </div>
  );
}