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"
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.