The code below has no IDE or compiler warnings, but is there a bug?
const MyComponent = (props: MyComponentProps) => {
const {loading, error, data} = useQuery(GET_ALL_USERS);
useEffect(() => {
props.onLoadingStateChange(loading);
}, [loading, props]);
return (
<UserList
{...props}
Take a moment to look at the code and think about it.
(If you answered yes, consider your answer correct.) Because the The fix: 💬 NOTEClick to Reveal the Answer
Answer: Yes! Kind of.
Technically, it's not a bug but a subtle performance pitfall.useEffect
depends on props
, it the side effect will run when any attribute inside props has changed.
const { onLoadingStateChange } = props; // destructure, so the dependency array is more specific
useEffect(() => {
onLoadingStateChange(loading);
}, [loading, onLoadingStateChange]);
This might seem like a contrived example that doesn't happen in real life, but I assure you: seeing this during code review prompted me to write the article.
Did you get it right? Please don't spoil the answer in the comments.
❤️ - you got it right
🤯 - didn't get it right, but learned something
Top comments (0)