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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay