Documenting Custom Hook Functions with JSDoc

7 views
Skip to first unread message

Ori Swid

unread,
May 4, 2024, 11:57:41 AMMay 4
to JSDoc Users

I'm working on documenting custom hook code in React using JSDoc. I'm trying to find the best way to include documentation for the functions that the hook returns.

For example, consider the following code:

JavaScript
const useMyHook = () => { /** * a long and informative description for function 1 * @param {string} name * @returns {void} */ const function1 = (name) => { // function does something. console.log(name); }; /** * a long and informative description for function 2 * @returns {string} */ const function2 = () => { // function does something else return 'hello'; }; return { function1, function2 }; };

The only approach I've found that JSDoc supports is to define a typedef for the hook's return value and within that typedef, define the two functions:

/** * @typedef UseMyHookReturn * @property {(name:string) => void} function1 - short description for function 1. * @property {() => string} function2 - short description for function 2. */ /** * This is my hook * @returns {UseMyHookReturn} */ const useMyHook = () => { /** * a long and informative description for function 1 * @param {string} name * @returns {void} */ const function1 = (name) => { // function does something. console.log(name); }; /** * a long and informative description for function 2 * @returns {string} */ const function2 = () => { // function does something else return 'hello'; }; return { function1, function2 }; }; // Consumer of the hook only see the short function descriptions from the UseMyHookReturn typedef const { function1, function2 } = useMyHook();

The problem is that when someone uses the hook I've written, they only see the short function description from the UseMyHookReturn typedef, not the full description I've added to the function signature. Additionally, I have to write the function signature twice (once in the typedef definition and once above the function itself) and maintain any changes in two separate places.

Is there a way to import the full function definition and use it in the @typedef for the hook's return value?

Thank you for your assistance.

Reply all
Reply to author
Forward
0 new messages