Sometimes, we want to call the useEffect
hook conditionally with React.
In this article, we’ll look at how to call the useEffect
hook conditionally with React.
Call the useEffect Hook Conditionally with React
To call the useEffect
hook conditionally with React, we can check for the condition before running the code in the useEffect
callback.
For instance, we write:
import React, { useEffect, useState } from "react";
const wantAnswer = true;
export default function App() {
const [val, setVal] = useState();
const getAnswer = async () => {
const res = await fetch("https://yesno.wtf/api");
const json = await res.json();
setVal(json.answer);
};
useEffect(() => {
if (!wantAnswer) {
return;
}
getAnswer();
}, []);
return <div>{val}</div>;
}
to call getAnswer
only when wantAnswer
is true
in the useEffect
callback.
To do that, we check if wantAnswer
is false
.
And if it is, we use the return
statement to stop running the useEffect
callback.
Conclusion
To call the useEffect
hook conditionally with React, we can check for the condition before running the code in the useEffect
callback.