Custom hooks con React Context y TypeScript

Clase 14 de 31Curso de React Avanzado

Resumen

Domina un flujo claro para crear un sistema de notificaciones con estado global usando React context, un provider y un custom hook reutilizable. Verás cómo conectar componentes como Notification y NotificationButton en TypeScript, disparar un showNotification con un mensaje y aplicar renderizado condicional limpio.

¿Qué construirás con React context y un custom hook?

Crearás una arquitectura sencilla y efectiva para notificaciones. Se basa en un contexto que expone el mensaje y la función showNotification, un provider que envuelve la app y un custom hook que simplifica el acceso al contexto.

  • Estado global accesible desde múltiples componentes.
  • Provider que envuelve la aplicación en App.
  • Custom hook para consumir el contexto sin repetición.
  • Componentes Notification y NotificationButton.
  • Renderizado condicional con return null cuando no hay mensaje.

¿Cómo se integra el provider en App para el estado global?

La base está en envolver la UI con el NotificationProvider. Dentro, renders el título, la descripción, el componente Notification y el NotificationButton. Así, todos leen el mismo estado global.

// App.tsx
import { NotificationProvider } from './context/notificationContext';
import Notification from './components/Notification';
import NotificationButton from './components/NotificationButton';

export default function App() {
  return (
    <NotificationProvider>
      <h1>Transacción casi lista</h1>
      <p>Confirma para continuar con el proceso.</p>
      <Notification />
      <NotificationButton />
    </NotificationProvider>
  );
}

Además, se limpia el boilerplate inicial y se preparan estilos propios. El punto clave: todo componente dentro del provider puede leer y actualizar el contexto.

¿Cómo crear Notification y NotificationButton en TypeScript?

Aprovecharás un custom hook llamado useNotification para consumir el contexto con seguridad y sin repetir lógica. También aplicarás TypeScript y componentes funcionales.

¿Cómo luce el componente Notification?

Este componente lee el message desde el contexto. Si no hay mensaje, usa return null para no renderizar nada. Cuando existe, muestra un contenedor semántico con el texto.

// components/Notification.tsx
import { FC } from 'react';
import { useNotification } from '../hooks/useNotification';

const Notification: FC = () => {
  const { message } = useNotification();
  if (!message) return null;
  return (
    <aside>
      <p>{message}</p>
    </aside>
  );
};

export default Notification;

¿Cómo funciona el NotificationButton con onClick?

El botón invoca showNotification y envía un texto personalizado. Así, la notificación aparece usando el mismo estado global.

// components/NotificationButton.tsx
import { FC } from 'react';
import { useNotification } from '../hooks/useNotification';

const NotificationButton: FC = () => {
  const { showNotification } = useNotification();

  return (
    <button onClick={() => showNotification('✨ Tu transacción se ha realizado con éxito.')}> 
      confirmar transacción
    </button>
  );
};

export default NotificationButton;

¿Cómo se crea el custom hook con useContext?

Centraliza el acceso al contexto y agrega una verificación para detectar usos fuera del provider. Esto mejora la DX y evita errores silenciosos.

// hooks/useNotification.ts
import { useContext } from 'react';
import { NotificationContext } from '../context/notificationContext';

export function useNotification() {
  const context = useContext(NotificationContext);
  if (context === undefined) {
    throw new Error('useNotification debe usarse dentro de NotificationProvider');
  }
  return context;
}

En conjunto, aplicas estas habilidades y conceptos clave:

  • React context para compartir estado entre componentes.
  • Provider pattern para envolver la app.
  • Custom hook para reusar lógica y validar el contexto.
  • useContext para leer el estado global.
  • Renderizado condicional con return null.
  • Manejo de eventos con onClick.
  • Estructura de proyecto con carpetas components y hooks.
  • TypeScript con componentes funcionales.

¿Te gustaría proponer otro uso para este patrón con context, provider y un custom hook? Cuéntalo en los comentarios y construyamos más casos juntos.

      Custom hooks con React Context y TypeScript