I am learning useEffect Hook in React and I have a question based on its usage.
Following is the code, which is still working fine as expected without the use of useEffect
Hook.
My question is – if this code is working is it advisable to go ahead without adding useEffect
in code or I am missing some concept here.
I know there are other lifecycle methods that can be mimic in functional component using useEffect
hook, but for small cases like this is it advisable to take this approach ?
Code –
import { useState } from 'react';
export default function App() {
const [title, setTitle] = useState(null);
const [num, setNum] = useState(2);
// useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/todos/${num}`)
.then((response) => response.json())
.then((response) => {
const { title } = response;
setTitle(title);
});
// }, []);
return (
<div className="App">
<h1>useEffect Example</h1>
<pre>{title}</pre>
<button onClick={() => setNum(num + 1)}>Increment</button>
</div>
);
}
3
Answers
The main problem with this is that each time the component executes its code is going to fetch the API and that is not a thing that you may want.
Probably in this example you will not see any mayor difference (as the way that the code is working) but as soon as you add this component to a more complex tree it will start to behave unexpectedly.
It would be extremely advisable to use
useEffect
here. If yourApp
component re-renders for any reason, then your fetch logic will execute again.When you use
useEffect
with a dependency array, you ensure that the effect withinuseEffect
is only executed when that dependency changes.You should use useEffect here.
The reason is that without it you will be calling fetch() on every rerender which is most likely not the thing you want to do.
In this case title is probably a string and does not change so it will not break, but in most cases this would be a dead loop. I’m also pretty sure that for every click you are now doing two fetch() calls – one after increment, and one with the same data after updating title.
This will also be a problem if you add any other unrelated state to your component, because you will start spamming fetch() with unchanged data.