Return values of React API callback functions and lifecycle methods should have valid types

  • REACT_BAD_API_RETURN_VALUE
  • Error
  • Medium
  • react

This rule applies when the return value of a React API callback function or lifecycle method is invalid.

If an invalid value is returned from a callback function or lifecycle method, it may cause a problem when React uses the value. Even when no immediate problem occurs, the value becomes meaningless.

The callback functions and lifecycle methods which cause problem for an invalid return value are listed below with the valid return values:

  1. Callback passed as the first argument of React.useEffect(): function or undefined
  2. Callback passed as the first argument of React.lazy(): dynamic import()
  3. Lifecycle method render(): React element, array, fragment, portal, string, number, boolean, or null
  4. Lifecycle method shouldComponentUpdate(): truthy or falsy value except undefined
  5. Lifecycle method getDerivedStateFromProps(): any value except undefined
  6. Lifecycle method getSnapshotBeforeUpdate(): any value except undefined

In the above cases, since a specific value should be returned, it might be a programmer's mistake returning a wrong value or forgetting a return statement.

Also, this rule checks the following which need no return value:

  1. Callback passed as the first argument of forceUpdate()
  2. Callback passed as the second argument of setState()
  3. Lifecycle method componentDidMount()
  4. Lifecycle method componentDidUpdate()
  5. Lifecycle method componentWillUnmount()
  6. Lifecycle method componentDidCatch()
  7. Lifecycle method UNSAFE_componentWillMount()
  8. Lifecycle method UNSAFE_componentWillReceiveProps()
  9. Lifecycle method UNSAFE_componentWillUpdate()

In the above cases, returning a value has no effect.

Noncompliant Code Example

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

export function App({ foo }) {
  useEffect(() => {
    if (!foo) {
      return null; // REACT_BAD_API_RETURN_VALUE alarm
    }
    doSomething(foo);
  }, []);
  return <div>{foo}</div>;
}

Compliant Code Example

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

export function App({ foo }) {
  useEffect(() => {
    if (!foo) {
      return;
    }
    doSomething(foo);
  }, []);
  return <div>{foo}</div>;
}

Version

This rule was introduced in DeepScan 1.4.0-beta.

See

  • React API Reference

  • React Warning: useEffect must not return anything besides a function, which is used for clean-up. You returned null. If your effect does not require clean up, return undefined (or nothing).

Was this documentation helpful?