Search code examples
javascriptjsdoc

How do I document useState hooks with JSDoc?


I'm trying to use JSDoc to document the destructured parts of my react state hooks for example:

const [referenceState, setReferenceState] = useState(null);

Here, referenceState is of type Object, and setReferenceState expects an Object.

Based on some information online, I'm trying to do something along the lines of:

/**
* @param {Object} stateToSet
* @returns {GenericArray} current state and function to change value
*/
const [referenceState, setReferenceState] = useState(null);

But that doesn't generate anything..

Can someone please help me document referenceState and setReferenceState?


Solution

  • I think you can try this approach:

    /**
     * @typedef {Object} ReferenceState
     */
    
    /**
     * @callback ReferenceStateSetter
     * @param {ReferenceState} state
     * @returns {void}
     */
    
    /**
     * @namespace {Object}
     * @property {ReferenceState} 0
     * @property {ReferenceStateSetter} 1 
     */
    const [referenceState, setReferenceState] = useState(null);
    

    Or, to avoid having to document the immediately destructured array, but benefiting from adding some indent changes at the end:

    /**
     * @typedef {Object} ReferenceState
     */
    
    /**
     * @callback ReferenceStateSetter
     * @param {ReferenceState} state
     * @returns {void}
     */
    
    const [
        /**
         * @type {ReferenceState}
         */
        referenceState,
    
        /**
         * @type {ReferenceStateSetter}
         */
        setReferenceState
    ] = useState(null);
    

    If you don't want to have documents for ReferenceState, you can get rid of its @typedef and replace references to it with Object, but I think it is clearer to have docs.

    void above is a simpler way to say nothing special (i.e., undefined) is returned--if that's what the setter returns. Some projects would just drop the @returns if it only returns undefined, but I like to add it to show the return value is known to be undefined and not merely undocumented.