Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
Can react hooks provide hooks?

This can probably be verified by a simple experiment. I was wondering if I can have a hook provide new hooks. For example given the following subscription manager

export interface SubscriptionManager<T = any> {
  /**
   *
   * @param fn function to call when notified.  It can be passed some data
   * @returns unsubscribe callback.
   */
  subscribe(fn: (data: T) => void): () => void;
  /**
   * Notify subscribers
   * @param data optionally pass data to the subscribers.
   */
  notify(data?: T): void;
}

/**
 * This hook provides a simple subscription semantic to React components.
 */
export function useSubscription<T = any>(): SubscriptionManager<T> {
  const subscribersRef = useRef<((data: T) => void)[]>([]);
  function subscribe(fn: (data: T) => void) {
    subscribersRef.current.push(fn);
    return () => {
      subscribersRef.current = subscribersRef.current.filter(
        (subscription) => !Object.is(subscription, fn)
      );
    };
  }
  function notify(data: T) {
    subscribersRef.current.forEach((fn) => fn(data));
  }
  return { subscribe, notify };
}

I want to generate a hook useSubcriptionEffect(fn) that prevents having to write boiler plate code like this

useEffect(() => subscribe(fn), []);

The Rules of Hooks only talk about "calls" but not "creation"

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I tried to do the experiment to confirm if it works and it appears to, but it looks weird because of the name and how it is generated, since most hooks are imported

The code is

import { useEffect, useRef } from "react";
import { SubscriptionManager } from "./SubscriptionManager";
/**
 * This hook provides a simple subscription semantic to React components.
 */
export function useSubscription<T = any>(): SubscriptionManager<T> {
  const subscribersRef = useRef<((data: T) => void)[]>([]);
  function subscribe(fn: (data: T) => void) {
    subscribersRef.current.push(fn);
    return () => {
      subscribersRef.current = subscribersRef.current.filter(
        (subscription) => !Object.is(subscription, fn)
      );
    };
  }
  function notify(data: T) {
    subscribersRef.current.forEach((fn) => fn(data));
  }
  function useSubscribeEffect(fn: (data: T) => void) {
    useEffect(() => subscribe(fn), []);
  }
  return { subscribe, notify, useSubscribeEffect };
}

The test appears to work

  it("should notify with clicks using generated hook", async () => {
    const callback = jest.fn();
    const MyContext = createContext<SubscriptionManager>({} as SubscriptionManager);
    function MyContextProvider({ children }: PropsWithChildren<{}>) {
      const { subscribe, notify, useSubscribeEffect } = useSubscription();
      return <MyContext.Provider value={{ subscribe, notify, useSubscribeEffect }}>{children}</MyContext.Provider>
    }
    function MyComponent() {
      const { useSubscribeEffect, notify } = useContext(MyContext);
      function onClick() {
        notify();
      }
      useSubscribeEffect(callback);
      return (<div data-testid="test" onClick={onClick}>abc</div>);
    }
    const { getByTestId } = render(<MyContextProvider><MyComponent /></MyContextProvider>)
    const element = getByTestId("test");
    expect(element.textContent).toEqual("abc");
    await waitFor(() => expect(callback).toBeCalledTimes(0));
    element.click();
    await waitFor(() => expect(callback).toBeCalledTimes(1));
    element.click();
    await waitFor(() => expect(callback).toBeCalledTimes(2));
  })

Code is in https://github.com/trajano/react-hooks-tests/tree/useSubscribeEffect still trying to see if the naming makes sense before I merge it in.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda