I use useEffect all the time in my applications, but I've never understood the difference between having code inside a useEffect with no dependency array, and just running it in the component itself.
From the documentation. What is the difference between this
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
}and this?
function Example() {
const [count, setCount] = useState(0);
document.title = `You clicked ${count} times`;
}wont both run on every render?
Edit: thanks for all the helpful responses. It seems like my intuition was almost right. It does behave slightly differently, but almost never in a way you want. However it would be good for protecting DOM manipulating functions for SSR.
I'm guessing the only difference is that useEffect will guarantee that it will always run after the render, it also makes sure that every other component that needs to re-render will finish rendering before running the effect.
Though I can't really think of a good use case for this.
more or less the same, but you wouldn't do either of these things. you'd use the useEffect with a dependency array that has count.
otherwise you're doing unnecessary work. say this Example components' parent rerenders which causes Example to rerender, now we're changing the document title even though count never changed.