12 Common useState & useEffect Pitfalls: A Guide for Junior React Developers in 2023

<h1>1/12 &mdash; Fetching in useEffect</h1> <ul> <li>A post component may keep track of an ID, and may also render during this post-body component. If you pass an ID to a post component, the post body may fetch some posts, and you may get a touchscreen problem.</li> <li>I like to extract this into its own separate type post body props and define that up here. Then we make a fetch call to some dummy API based on the ID and get some response which we parse as Json and convert to normal JavaScript objects.</li> <li>We want to be able to change the ID of a post whenever we click on a button, and then fetch a new post based on the ID. So we can say math.random To get a random number between 0 and 1 we want to do that times 100.</li> <li>We get a random number between 0 and 100, round it up or down, and then change the ID to some random number. Now, if we click here, it should fetch a new post, but it doesn&rsquo;t because the use effect only runs when the component first mounts.</li> <li>Alright so far so good. However, in the real world, we need to think about edge cases as well, and if we click multiple times quickly after another, we get five set text very quickly one after another.</li> <li>If you want to become a professional developer, you have to think about and solve problems like this. So you can have a new abort controller and attach a signal to it to cancel the fetch.</li> <li>User Thanks has a cleanup function that runs whenever you unmount the components and also before you go for another round of the use effect. We can use this function to abort the previous fetch call and show the last one instead of flashing through them.</li> <li>If we remove all of this, we see a race condition where the different fetches are basically racing against each other to see which one will set the text first or last. There are other problems as well, like caching and loading state.</li> <li>If you have an error with fetching, you have to keep track of that in the error State. You should try fetching data in the server component, or use a library like React Query or Swr by for cell next to us.</li> <li>All of this is going to be very easy if you have picked up the fundamentals, so make sure you master React and JavaScript and learn Css properly.</li> </ul> <p>&nbsp;<a href="https://medium.com/@roshan.waa/12-common-usestate-useeffect-pitfalls-a-guide-for-junior-react-developers-in-2023-8343496f2112">Read More</a></p>
Tags: React Pitfalls