Besides the cleanup and the dependency array, is there any reason to use useEffect
?
function App() {
const [a, setA] = useState(0);
const b = `Number: ${a}`;
return (
<div className="App">
<p>
{b}
</p>
<button onClick={() => setA(a + 1)}>click</button>
</div>
);
}
As we can see, we don't use the useEffect
, but as changing state a
will trigger re-rendering, then also b
will be changed. It looks like we don't even need the useEffect
in this case.
So is there any unique benefit from the useEffect
except for the cleanup and the dependency array?
Edit
I think most of the answers are based on one assumption: The OP has a good understanding of the react life-cycle logic. But unfortunately, that's my weakness.
Although I used the useEffect
and those old component*
life-cycle methods a lot, I didn't really realize that those are something outside of the function component itself. Which gives them more flexibility and functionalities.
I am not trying to insult anyone, but I do think that we should answer the question more specifically and carefully. Anyone traverses my profile can see that I also answered a lot of questions. Based on my experience, people usually lack the knowledge to even ask a critical and clear question, they don't even realize what is the key point(Yes, I am one of them in this question).
When I am trying to answer the question, I will first try to clarify the question to understand what is the critical piece that the OP is missing.
@PatrickRoberts was exactly saying something which is correct, but that didn't really help me as that is not the piece I was missing. I would insult myself that I didn't make the question clear enough. But I also want to say that, understanding/clarifying the question is more important than giving the correct answer. After all, theoretically, most of the questions can be solved by official documents.