Using specific APIs inside React.render()
should be avoided
- REACT_MISUSED_API_IN_RENDER
- Error
- Medium
- react
This rule applies when specific APIs are used inside React.render()
.
The below APIs cannot be used inside React.render()
because it triggers nested component updates or accesses unmounted components:
ReactDOM.render()
ReactDOM.unmountComponentAtNode()
ReactDOM.findDOMNode()
In the above cases, React outputs a warning message. Therefore, these APIs should be called inside componentDidUpdate()
or componentDidMount()
instead of React.render()
.
For your reference, using setstate()
inside React.render()
also triggers the nested component updates. This case is detected by REACT_BAD_UPDATE_STATE rule.
Noncompliant Code Example
View with compliant examples side by sideimport React from 'react';
import ReactDOM from 'react-dom';
export class MyComponent extends React.Component {
render() {
ReactDOM.findDOMNode(this.node).focus(); // REACT_MISUSED_API_IN_RENDER alarm because the component is not mounted yet.
return (
<div>
<input type="text" ref={(node) => this.node = node} />
</div>
);
}
}
Compliant Code Example
View with noncompliant examples side by sideimport React from 'react';
import ReactDOM from 'react-dom';
export class MyComponent extends React.Component {
componentDidMount() {
ReactDOM.findDOMNode(this.node).focus();
}
render() {
return (
<div>
<input type="text" ref={(node) => this.node = node} />
</div>
);
}
}
Version
This rule was introduced in DeepScan 1.6.0-beta.
See
React Warning: A component is accessing findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.