Home > Article > Web Front-end > What is the usage of forceupdate in react
In react, forceupdate() is used to force the component to skip shouldComponentUpdate() and directly call render(), which can trigger the normal life cycle method of the component. The syntax is "component.forceUpdate(callback)".
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
A component in React will re-render only when the state of the component or the props passed to it change, but if some data Changes, if we need to change the re-render of a component, then we will use React's forceUpdate() method. Calling forceUpdate() will force the component to re-render, thus skipping the shouldComponentUpdate() method and calling the component's render() method.
Tip: In general, avoid using forceUpdate() and only read from this.props and this.state in render().
Usage:
component.forceUpdate(callback)
While there are indeed some use cases for using the forceUpdate() method, it is best to use hooks, props, state and context to re-render components when needed.
By default, the component will re-render when its state or props change. If your render() method depends on some other data, you can tell the React component that it needs to re-render by calling forceUpdate().
Calling forceUpdate() will cause the component to skip shouldComponentUpdate() and call render() directly. This will trigger the component's normal lifecycle methods, including the shouldComponentUpdate() method of each child component.
forceUpdate is to re-render. Some variables are not in the state, and you want to refresh the render when the variable is updated; or a variable in the state is too deep, and the render is not automatically triggered when updated. At these times, you can manually call forceUpdate to automatically trigger render
Sub.js class Sub extends React.Component{ construcotr(){ super(); this.name = "yema"; } refChangeName(name){ this.name = name; this.forceUpdate(); } render(){ return (<div>{this.name}</div>); } } App.js class App extends React.Component{ handleClick(){ this.subRef.refChangeName("yemafuren"); } render(){ return (<div> <Sub ref={(sub)=>{this.subRef = sub;}} /> <button onClick={this.handleClick}>click</button> </div>); } }
Recommended learning: "react video tutorial"
The above is the detailed content of What is the usage of forceupdate in react. For more information, please follow other related articles on the PHP Chinese website!