am learning useEffect
and the way it works.
For now I am passing a function into my useEffect. After this I get the message:
React Hook useEffect has a missing dependency: 'handleSearch'. Either include it or remove the dependency array.
I tried to wrap everything into a useCallback, but then the app just crashes. I suuspect, that useEffect is rerendering my function on every change, so I would like to prevent it. Hope that someone can help me.
Here is some of my code:
const App = () => {
const API_KEY = process.env.REACT_APP_API_KEY;
const [ videos, setVideos ] = useState([]);
const [ searchedValue, setSearchedValue ] = useState({
selectedVideo: null
});
const handleSelectedVideo = (singleRenderedVideo) => {
setSearchedValue((previous) => ({
...previous,
selectedVideo: singleRenderedVideo
}));
};
const handleSearch = async (inputText) => {
const response = await youtube.get("/search", {
params: {
q: inputText,
part: "snippet",
type: "video",
maxResults: 16,
key: API_KEY
}
});
setVideos(response.data.items);
setSearchedValue({
selectedVideo: response.data.items[0] //take the first search result and make it appear as a playable one
});
};
useEffect(() => {
handleSearch();
}, []);
return (
<div>
Hello
</div>
);
};
export default App;
I tried to deal with it with useCallback, but it didnt help, just got a 403:
const handleSearch = useCallback(
async (inputText) => {
const response = await youtube.get("/search", {
params: {
q: inputText,
part: "snippet",
type: "video",
maxResults: 16,
key: API_KEY
}
});
setVideos(response.data.items);
setSearchedValue({
selectedVideo: response.data.items[0] //take the first search result and make it appear as a playable one
});
},
[ API_KEY ]
);
useEffect(
() => {
handleSearch();
},
[ handleSearch ]
);
Why should I include (according to Eslint) API_KEY as dependency if it never changes?
I tried to mockup the code in Sandbox. Sorry, that it is not working because of the API_KEY: CODESANDBOX