How to handle rest arguments in useEffect

A few days ago, I was trying to create a React Hook passing rest arguments. I wanted these arguments to trigger useEffect each time they changed. So, my first approach was to build something like this:

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

const useExample = (...args) => {
    
    useEffect( () => {
    
        // Some code here to do stuff
        
    }, [args]);
    
}

export default useExample;

Rest arguments causing infinite rerender

React consider rest arguments as a new array on each render. Finding solutions, I came to this thread on GitHub. A user proposed to hash the arguments to generate a value to compare against.

Instead of hashing, I tried to use a function returning a constant result: JSON.stringify() did the job. ✌️

Solution

Solution was using JSON.stringify() with rest arguments.

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

const useExample = (...args) => {
    
    useEffect( () => {
    
        // Some code here to do stuff
        
    }, [JSON.stringify(args)]);
    
}

export default useExample;

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