How to reset a custom Hook in React

Let's assume that you create a custom Hook in React that counts clicks:

jsx
import React, { useEffect, useState } from 'react';

const useNumberClicks = () => {
    
    const [clicks, setClicks] = useState(0);
    
    useEffect(() => {
        
        const handleClick = () => setClicks(clicks + 1);
        
        document.addEventListener('click', handleClick);
        
        return () => document.removeEventListener('click', handleClick);
        
    }, [clicks]);
    
    return clicks;
    
} 

export default useNumberClicks;

Now, let's assume that you want to use this Hook in the main component:

jsx
import React           from 'react';
import useNumberClicks from './useNumberClicks';

const App = () => {
    
    const numberClicks = useNumberClicks();
    
    return(
        <div>
            Number of clicks is {numberClicks}.
        </div>
    );
}

export default App;

Return variable and function to reset

Let's assume that you wanted to reset the Hook when the mouse hovers the text.

Instead of returning only the number of clicks in the Hook, you could also return the function to reset the number of clicks:

jsx
import React, { useEffect, useState } from 'react';

const useNumberClicks = () => {
    
    const [clicks, setClicks] = useState(0);
    
    useEffect(() => {
        
        const handleClick = () => setClicks(clicks + 1);
        
        document.addEventListener('click', handleClick);
        
        return () => document.removeEventListener('click', handleClick);
        
    }, [clicks]);
    
    return [clicks, setClicks];
    
} 

export default useNumberClicks;

At this point, is straightforward to reset the number of clicks from the main component:

jsx
import React           from 'react';
import useNumberClicks from './useNumberClicks';

const App = () => {
    
    const [numberClicks, setNumberClicks] = useNumberClicks();
    
    return(
        <div  onMouseOver = {() => setNumberClicks(0)}>
            Number of clicks is {numberClicks}. Hover to reset counter.
        </div>
    );
}

export default App;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.