This example is given in the react documentation to describe the use of useEffect.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Could this not be re-written without using useEffect as below? Why is useEffect preferred?
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
const handleChange = () => {
setCount(count + 1);
document.title = `You clicked ${count} times`;
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleChange}>
Click me
</button>
</div>
);
}
You clicked {count} times
' does update correctly? – Sam Archer Dec 05 '21 at 04:24