Minimal React hello world example. As you click:By opening a web inspector, you can see that only modified elements get updated. So we understand that JSX parses its "HTML-like" into a tree, and then propagates updates on that tree.
- one counter increments every time
- the other increments every two clicks
By looking at the terminal, we see that
render()
does get called every time the button is clicked, so the tree of elements does get recreated every time. But then React diffes thing out and only updates things in the DOM where needed.react/hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<p><a href="https://cirosantilli.com/_file/react/hello.htmlhttps://cirosantilli.com/react">https://cirosantilli.com/_file/react/hello.html</a></p>
<div id="root"></div>
<script type="text/babel">
class Main extends React.Component {
constructor(props) {
super(props)
console.log('Main.constructor')
this.state = {n: 0}
}
render() {
console.log('Main.render')
return (
<div>
<button
onClick={
() => {
console.log('onClick')
this.setState((state, props) => ({
n: state.n + 1
}))
}
}>Click me</button>
<div>n = {this.state.n}</div>
<div>n/2 = {Math.floor(this.state.n / 2)}</div>
</div>
)
}
}
ReactDOM.createRoot(document.getElementById('root')).render(<React.StrictMode><Main /></React.StrictMode>)
</script>
</body>
</html>