Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda