I would like to understand why useEffect is being used at the bottom of the code-block, and which purpose it serves. I think it has something to do with the component life-cycle and avoiding an infinite loop, but I can't quite wrap my head around it and get the big picture of it all. I am very thankful if somebody could explain to me what happens behind the scenes, and what influence the usage of the useEffect block has. Thank you very much!
const Films = () => {
const [filmDataState, setFilmDataState] = useState();
const [loadingState, setLoadingState] = useState();
const [errorState, setErrorState] = useState(false);
const getFilmsHandler = useCallback(async () => {
setLoadingState(true);
try {
const response = await fetch(
process.env.REACT_APP_DBLINKMOVIES,
{ method: "GET", headers: { "Content-Type": "application/json" }, }
);
const data = await response.json();
console.log(data);
let filmArray = [];
for(const key in data){
filmArray.push({
key: key,
title: data[key].title,
crawl: data[key].openingText
})
}
console.log(filmArray);
setFilmDataState(filmArray);
setLoadingState(false);
} catch (error) {
setErrorState(error.message);
}
}, []);
useEffect(() => {
getFilmsHandler();
}, [getFilmsHandler]);
CodePudding user response:
The shortest answer I can think of without just linking the documentation from react is that the useEffect block (with an empty dependency array) ensures that the code within the block is only run once. Or when adding dependencies to the dependency array, it will run again when any of these dependencies change.
The most important thing to keep in mind that when the state of a component change it re-render.
If you didn't have the useEffect. Your component would fetch data, which would update the state of the component, which would trigger a rerender of the component, which would cause another fetch of the data, and so on and so forth.
CodePudding user response:
useEffect is a React hook and we put at the bottom of the code to take priority at this block of the code. It is basically a hook replacement for the "old-school" lifecycle methods componentDidMount, componentDidUpdate and componentWillUnmount. It allows you to execute lifecycle tasks without a need for a class component.