The dependency of a React Hook should not be specified with a newly created object

  • REACT_USELESS_DEPENDENCY_OF_HOOK
  • Code Quality
  • Low
  • react

This rule applies when the dependency of a React Hook is specified with a newly created object.

The dependencies array argument of a React Hook controls the execution of the Hook. When none of the dependencies change from the previous render, the Hook execution will be skipped.

However, when a fresh object created at the current render is used as a dependency, the dependent Hook will always re-run because reference equality is used. This may not be a programmer's intent.

Noncompliant Code Example

View with compliant examples side by side
import React, { useEffect } from 'react';

export function HelloColor(props) {
    let style = { color: props.color };
    useEffect(
        () => { doSomething(style); },
        [style] // REACT_USELESS_DEPENDENCY_OF_HOOK alarm because 'style' object is always newly created.
    );
    return <div style={style}>Hello</div>;
}

Compliant Code Example

View with noncompliant examples side by side
import React, { useEffect, useMemo } from 'react';

export function HelloColor(props) {
    let style = useMemo(() => ({ color: props.color }), [props.color]);
    useEffect(
        () => { doSomething(style); },
        [style]
    );
    return <div style={style}>Hello</div>;
}

Version

This rule was introduced in DeepScan 1.30.0.

See

Was this documentation helpful?