Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
¿Pueden los ganchos de reacción proporcionar ganchos?

Esto probablemente puede ser verificado por un experimento simple. Me preguntaba si puedo hacer que un gancho proporcione nuevos ganchos. Por ejemplo, dado el siguiente administrador de suscripciones

 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 }; }

Quiero generar un gancho useSubcriptionEffect(fn) que evite tener que escribir un código de placa de caldera como este

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

Las Reglas de Hooks solo hablan de "llamadas" pero no de "creación"

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Intenté hacer el experimento para confirmar si funciona y parece que funciona, pero se ve raro por el nombre y la forma en que se genera, ya que la mayoría de los ganchos son import .

el codigo es

 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 }; }

La prueba parece funcionar

 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)); })

El código está en https://github.com/trajano/react-hooks-tests/tree/useSubscribeEffect todavía tratando de ver si el nombre tiene sentido antes de fusionarlo.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!