EN
React - class component force re-render
0
points
In this article, we would like to show you how to force re-render in a class component in React.
Any change of state causes component rendering, so using e.g. counter
in the state, we are able to force re-rendering always when setState()
method changes (increments) the value of our counter
.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
render() {
console.log('App component rednering...');
return (
<div>
<button onClick={() => this.setState({ counter: this.state.counter + 1 })}>
force re-rendering
</button>
</div>
);
}
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Note:
Go to this article to see functional component example.