In most react examples I have seen, people seem to avoid placing code directly into a functional component's body but instead are wrapping it into useEffect(() => {...})
.
E.g. in the official docs:
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Why is this better than simply writing:
function Example() {
const [count, setCount] = useState(0);
document.title = `You clicked ${count} times`;
return (...);
}
In both cases the document title will be set on each render. (I believe with useEffect()
the code is executed after render, but that doesn't seem to be relevant in this example, right)
I understand the value of useEffect()
if:
- States are passed as a second parameter so the code won't be executed on every render but with respect to the specified state changes.
- We take advantage of the cleanup mechanics.
But without that? Is there still a reason to wrap your code into useEffect()
?