I just want to know the difference of both options.
Option 1: Outside UseEffect
const [data, setData] = useState(null);
const getData = async () => {
try {
const response = await fetch("https://catfact.ninja/fact");
const result = await response.json();
setData(result);
} catch(error) {
}
};
useEffect(() => {
getData();
}, [])
return (
<>
<h1>{data?.fact}</h1>
</>
)
}
option 2: Inside useEffect
const [data, setData] = useState(null);
useEffect(() => {
const getData = async () => {
try {
const response = await fetch("https://catfact.ninja/fact");
const result = await response.json();
setData(result);
} catch(error) {
}
};
getData();
}, [])
return (
<>
<h1>{data?.fact}</h1>
</>
)
I saw that both of them do the same thing but what is the difference and how to perform clean up function for both options and when should I use the option 1 and option 2.
3
Answers
If you function is inside useEffect. You can’t access it from outside. But when your function is outside of useEffect you can call it within your component and inside useEffect also.
Using a function outside the
useEffect
is more performant. It does not recreated on re-render.If you consider using variables present in the component, then based on their scopes, your function’s ability to access them will differ.
Also, the function call inside and outside the useEffect will behave differently.
In a component,
function on every render of component.
the useEffect, you can control when you want to execute the function
by using dependency array of useEffect hook.
Regarding clean up function also, if you can access it inside useEffect, there is no difference in its execution. It will execute when the component unmounts.