React: useEffect() Dependencies Questions?
I'm watching the video:
React JS Full Course for Beginners | Complete All-in-One Tutorial | 9 Hours
https://www.youtube.com/watch?v=RVFAyFWO4go
(Specifically, Chapter 19: Axios API Requests at 6:29:42)
I tried to get ahold of the video?s author, but no luck?
The example shown in the video uses the following code:
Code:
const EditPost = ({
posts, handleEdit, editBody, setEditBody, editTitle, setEditTitle
}) => {
const { id } = useParams();
const post = posts.find(post => (post.id).toString() === id);
useEffect(() => {
if (post) {
setEditTitle(post.title);
setEditBody(post.body);
}
}, [post, setEditTitle, setEditBody])
return (
<div> nothing here yet... </div>
)
}
Why are post, setEditTitle, and setEditBody included in the useEffect() dependency array? What effect does including them have? Why is useEffect() needed at all here? Can't we just set the values directly?
Thanks, just please be sure to review CH 19 in this video, it will explain everything that I am asking about...
Re: React: useEffect() Dependencies Questions?
The useEffect in that example runs whenever any of its dependencies change ? here that?s post, setEditTitle, and setEditBody.
In reality, the two setter functions from useState (setEditTitle and setEditBody) never change between renders, so they don?t need to be in the dependency array. The only real dependency here is post, because that?s what determines the title and body values you?re setting.
A cleaner version of the code would be:
Quote:
useEffect(() => {
if (post) {
setEditTitle(post.title);
setEditBody(post.body);
}
}, [post]);
The reason they appear in the video?s code is likely because the author had ESLint?s ?exhaustive-deps? rule enabled, which warns you to include everything referenced inside useEffect. In this case, including the setters is harmless but unnecessary.
Re: React: useEffect() Dependencies Questions?
Thanks man. I downloaded the source code and played around with it. Now I understand how it all works!
Re: React: useEffect() Dependencies Questions?
Basically, useEffect stops the setters from running on every render (which would cause a loop). post is in there so it updates if you pick a different post. And the setters are just there because the linter nags you to include everything?safe habit, even though they don?t change.