← React & TypeScript

Coding challenge

create a custom hook useToggle that:

Challenge: create a custom hook useToggle that:
- Takes an optional initial value (defaults to false).
- Returns a tuple: [currentValue, toggleFunction].
- The function must toggle between true and false.

Tests: use-toggle.test.tsx — try to solve it before reading the solution below.
Show solution
// Reto: crea un custom hook useToggle que:
// - Reciba un valor inicial opcional (por defecto false).
// - Devuelva una tupla: [valorActual, funcionParaAlternar].
// - La función debe alternar entre true y false.
//
// Tests: use-toggle.test.tsx — intenta resolverlo antes de leer la solución de abajo.

import { useCallback, useState } from "react";

// El tipo de retorno es una TUPLA tipada: [boolean, () => void].
// Sin esta anotación, TypeScript inferiría (boolean | (() => void))[]
// y perderíamos la posición exacta de cada elemento.
export function useToggle(inicial = false): [boolean, () => void] {
  const [activo, setActivo] = useState(inicial);

  // useCallback mantiene la misma referencia de la función entre renders.
  // Usamos la forma funcional (v => !v) para no depender del valor actual.
  const alternar = useCallback(() => setActivo((v) => !v), []);

  return [activo, alternar];
}