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]);