DEV Community

Lem Dulfo
Lem Dulfo

Posted on

1 1

Pop Quiz: Is There a Bug in This React Native Component?

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}
Enter fullscreen mode Exit fullscreen mode

Take a moment to look at the code and think about it.


Click to Reveal the Answer
Answer: Yes! Kind of.

(If you answered yes, consider your answer correct.)
Technically, it's not a bug but a subtle performance pitfall.

Because the useEffect depends on props, it the side effect will run when any attribute inside props has changed.

The fix:

  const { onLoadingStateChange } = props; // destructure, so the dependency array is more specific
  useEffect(() => {
    onLoadingStateChange(loading);
  }, [loading, onLoadingStateChange]);
Enter fullscreen mode Exit fullscreen mode

💬 NOTE
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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay