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:
- Callback passed as the first argument of
React.useEffect()
: function orundefined
- Callback passed as the first argument of
React.lazy()
: dynamicimport()
- Lifecycle method
render()
: React element, array, fragment, portal, string, number, boolean, ornull
- Lifecycle method
shouldComponentUpdate()
: truthy or falsy value exceptundefined
- Lifecycle method
getDerivedStateFromProps()
: any value exceptundefined
- Lifecycle method
getSnapshotBeforeUpdate()
: any value exceptundefined
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:
- Callback passed as the first argument of
forceUpdate()
- Callback passed as the second argument of
setState()
- Lifecycle method
componentDidMount()
- Lifecycle method
componentDidUpdate()
- Lifecycle method
componentWillUnmount()
- Lifecycle method
componentDidCatch()
- Lifecycle method
UNSAFE_componentWillMount()
- Lifecycle method
UNSAFE_componentWillReceiveProps()
- Lifecycle method
UNSAFE_componentWillUpdate()
In the above cases, returning a value has no effect.
Noncompliant Code Example
View with compliant examples side by sideimport { 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 sideimport { 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 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).