How NOT to Fetch Data in React | Lecture 139 | React.JS đ„
Summary
TLDRThe script discusses the incorrect way of loading data into a React application, which serves as a valuable learning experience. It demonstrates the pitfalls of updating state within the render logic, leading to an infinite loop of state setting and component re-rendering. By breaking this rule intentionally, the instructor aims to reinforce React's best practices and the importance of separating side effects from the render logic. The script walks through fetching movie data from an API and showcases the consequences of setting state directly, resulting in excessive API requests and potential errors. Ultimately, it sets the stage for introducing the useEffect hook as the correct solution in the subsequent lecture.
Takeaways
- đ« Never update state in React's render logic (code at the top level of the component function), as it can cause an infinite re-rendering loop.
- đ„ Breaking rules intentionally can be an effective way to learn React and its principles better.
- đ The script demonstrates fetching data from an external API (OMDb) and handling the asynchronous response.
- đ When using external APIs, it is best practice to store the API key in a separate variable outside the component function.
- â»ïž Setting state in the render logic causes the component to re-render, which in turn re-executes the render logic, leading to an infinite loop.
- đ°ïž Updating state with an empty array or directly setting watched triggered the 'too many re-renders' error due to the infinite loop.
- đŁ The useEffect hook is introduced as the solution to handle side effects like data fetching correctly in React components.
- đ For those unfamiliar with asynchronous JavaScript and the fetch API, the script recommends reviewing the relevant sections from earlier in the course.
- đ Each time a component re-renders, the entire function (render logic) is executed again, including any variable definitions within it.
- đ§ Defining variables that don't depend on component state or props outside the component function is a good practice to avoid unnecessary re-computations.
Q & A
What is the purpose of this lecture?
-The purpose of this lecture is to demonstrate the improper way of fetching data in a React application and then introduce the correct approach using the useEffect hook, which will be covered in the next lecture.
Why is it considered wrong to update state in render logic?
-Updating state in render logic introduces a side effect, which is an interaction with the outside world. React's render logic should be free of side effects to prevent infinite re-rendering loops and maintain the application's stability.
What happens when state is set within the top-level code of the component function?
-Setting state within the top-level code of the component function triggers an infinite loop of state updates and re-renders. This is because updating the state causes the component to re-render, which in turn re-executes the top-level code, leading to an endless cycle.
How is the OMDb API used in this example?
-The OMDb API is used to fetch movie data based on a search query. The instructor demonstrates how to construct the API request URL, obtain an API key, and make the fetch request using the Fetch API in JavaScript.
Why is it recommended to define variables outside the component function?
-Variables that do not depend on anything inside the component should be defined outside the component function. This is because the entire function is re-executed during each render, and defining variables inside would lead to unnecessary re-creation of those variables.
What is the purpose of the `.then()` method used with the `fetch` function?
-The `.then()` method is used to handle the promise returned by the `fetch` function. It allows you to access the response data and perform additional operations, such as converting the response to JSON format.
Why does the instructor suggest breaking rules in this lecture?
-The instructor suggests breaking the rule of not updating state in render logic as a learning experience. By intentionally violating this rule, students can better understand why the rule exists and the consequences of breaking it.
What is the potential issue with making multiple fetch requests in quick succession?
-Making multiple fetch requests in quick succession can lead to excessive network traffic, performance degradation, and potential API rate limiting issues. It's generally advisable to implement appropriate throttling or caching mechanisms to avoid overloading the API with requests.
What is the significance of the 'too many re-renders' error mentioned in the lecture?
-The 'too many re-renders' error is a warning from React indicating that the component is entering an infinite loop of re-rendering, which can lead to performance issues and potential crashes. This error is triggered when state updates are occurring in an uncontrolled manner within the render logic.
What is the solution proposed to address the issue of updating state in render logic?
-The solution proposed is to use the useEffect hook, which will be covered in the next lecture. The useEffect hook allows developers to perform side effects, such as data fetching, in a controlled and predictable manner, preventing the infinite re-rendering loop.
Outlines
đ Setting Up Data Fetching in React the Wrong Way
The paragraph explains how to fetch movie data from the OMDb API using the fetch function in React. It involves getting an API key, constructing the API URL with the movie query, and making the fetch request inside the component's render logic. However, it warns that fetching data and setting state in the render logic is considered the wrong approach and will lead to an infinite loop of re-renders, causing performance issues.
â ïž Consequences of Setting State in Render Logic
This paragraph demonstrates the problems that arise when state is set in the render logic of a React component. It shows that setting state in the top-level code of the component function leads to an infinite loop, causing the component to re-render continuously. This results in an excessive number of API requests and, in some cases, React's 'too many re-renders' error. The paragraph emphasizes that setting state in render logic should be avoided, and the use of the useEffect hook is recommended as the correct approach, which will be covered in the next lecture.
Mindmap
Keywords
đĄData Fetching
đĄSide Effects
đĄRender Logic
đĄState Management
đĄuseEffect Hook
đĄAPI Key
đĄPromises
đĄAsynchronous JavaScript
đĄInfinite Loop
đĄNetwork Tab
Highlights
In this lecture, we are going to break the rule of not updating state in render logic, so that we can understand why it exists in the first place.
Breaking rules is a great way of learning React and its rules better.
We will fetch movie data from the OMDb API as soon as the app component mounts for the first time.
Defining variables outside the component function prevents them from being recreated on every re-render.
Fetching data and updating state in the render logic introduces a side effect, which should never be allowed.
Updating state in render logic causes an infinite loop of state setting and re-rendering.
React will throw an error for too many re-renders if state is set directly in the top-level render logic.
To set state after fetching data without causing an infinite loop, we need to use the useEffect hook.
Defining variables outside the component function is a good practice to prevent unnecessary re-creation.
Fetching data from an API is an interaction with the outside world and should not be done in render logic.
Logging data to the console in render logic appears to work fine, but updating state causes issues.
Infinite loops of state setting and re-rendering can lead to performance issues and potentially crash the application.
React's strict mode helps catch potential issues like too many re-renders during development.
The useEffect hook is the correct way to handle side effects like data fetching in React components.
Breaking rules intentionally is a valuable learning experience to understand the rationale behind React's best practices.
Transcripts
â«Let's now load some data
â«into a React application for the very first time.
â«However, in this lecture,
â«let's start by doing it the wrong way basically,
â«which is going to be a great learning experience.
â«So in this section,
â«we are going to go back to our usePopcorn application
â«that we have been working on before.
â«And so let's now grab the project folder
â«and open it back up in VS code.
â«All right, now here
â«let's start by actually duplicating this file
â«and then I'm gonna rename one of them to app version one.
â«And so by doing this, we are not going to override the code
â«that we have written before.
â«And so you can keep it as a reference.
â«Now, as we have learned before in the previous section,
â«we should never update state in render logic, right?
â«But now in this lecture, let's actually break that rule
â«so that we can see
â«why it actually exists in the first place.
â«And breaking rules like this
â«is actually a pretty great way of learning Reacts
â«and also its rules even better.
â«Now, the idea here is to fetch some movie data
â«as soon as the app component here
â«mounts for the very first time,
â«so as soon as it has its initial render.
â«So to fetch that data, we use the OMDb API,
â«which is basically like an open version of IMDB.
â«Now to get started, you need to get your own API key,
â«which you can get for free just by clicking here
â«and then filling out this form.
â«And so immediately you will then get your free API key.
â«Now then once you have that, you can just come back here
â«to the main page so we can see how we can use this API.
â«So our data requests should simply be sent to this URL.
â«So just copy that.
â«And then here, let's fetch the data using the fetch API.
â«So using the fetch function like this.
â«Now, right.
â«Now, in case you're not familiar with the fetch function
â«and on how to work with asynchronous JavaScript,
â«then please go back to the beginning of the course
â«and take a look at the JavaScript review section
â«where I talk about all that in great length.
â«But anyway here now of course
â«you need to place your own key.
â«And actually I want to do this,
â«so I want to place this key in a separate variable.
â«So let's define that out here.
â«So key and by now, after that long previous section
â«you know why we should actually define a variable like this
â«outside the component function.
â«And the reason for that is that each time
â«the component gets re-rendered
â«this entire function here will be executed again.
â«So basically all the render logic.
â«And so if this variable definition here
â«is part of that render logic
â«it'll also be recreated each time data component renders,
â«which is in this case, of course, not a big deal
â«but it's good to already get
â«into the habit of not doing that.
â«So when you're just defining a variable like this
â«that doesn't depend on anything that's inside the component,
â«then just declare it outside.
â«Now I'm just getting my own API key,
â«but of course you should use your own one here.
â«And now let's go back to the documentation page
â«where we can see that we can query the API in two ways.
â«So we can search for an ID or a title
â«or we can actually search by some query string.
â«And so that's actually what we will do here.
â«So here let's use S and then equal.
â«And then here you can type your favorite movie,
â«which for me probably is "Interstellar".
â«Not 100% sure of that, but it's definitely a great one.
â«Okay.
â«But anyway, now we need to handle the promise
â«that the fetch function here returns inside.
â«And of course here it's then, so inside a then method,
â«which gets access to the response
â«and then here we can convert that response
â«to Json immediately, which will return another promise.
â«And so we chain on another then
â«and then here we get access to the data,
â«which we can then for now log to the console.
â«And for now, that's actually it.
â«So let's see what we get here.
â«Or of course we first need to
â«actually start our application.
â«So make sure you are in the right project folder here
â«and then type npm start.
â«So that should then open up the new tab here.
â«And indeed, there it is.
â«So let's check out our console
â«and let's just reload quickly.
â«And indeed you see that React was able
â«to fetch the data from the API.
â«So we are just interested in the search here.
â«And so all the movies here are in fact about "Interstellar",
â«which means that our query here is already working.
â«Now as we learned in the previous section,
â«this data fetching that we're doing right here is actually
â«introducing a side effect into the component's render logic.
â«So it is clearly an interaction with the outside world,
â«which should never be allowed in render logic.
â«So again, all this code that is here
â«at the top level of the function is of course
â«code that will run as the component first mounts
â«and therefore it is called render logic.
â«And so again, here we should have no side effects.
â«I mean, in this example
â«where we only log something to the console,
â«it actually appears to work just fine,
â«but watch what happens if we set some state here.
â«And to do that
â«let's actually first get rid of our temporary data here.
â«So this movie data and watched data
â«we only used as a template for the previous section,
â«but now let's get rid of that.
â«And so as I was just saying,
â«let's now here actually set state.
â«So that list of movies that we get from the API
â«we now want to get it into our movie state.
â«And so that's at data.search.
â«Give it a save and beautiful.
â«So we got some data from the API now showing up in our UI,
â«but watch what happens when we check out the network tab.
â«So you see that it's basically running
â«an infinite number of requests here, so it keeps going
â«and it never really stops.
â«So every second our app is firing off
â«multiple fetch requests to this API,
â«which of course is a really, really bad idea.
â«So why do you think that is?
â«Why do you think all these fetch requests
â«are being fired off?
â«Well, the reason is that setting the state here
â«in the render logic will then immediately
â«cause the component to re-render itself again.
â«So that's just how state works, right?
â«However, as the component is re-rendered,
â«the function here of course is executed again,
â«which then will fetch again,
â«which in turn will set the movies again as well.
â«And then this whole thing starts over and over again.
â«So as the state instead the component is re-rendered again,
â«which then will fetch again,
â«which will set the movies again.
â«And so this really is an infinite loop of state setting
â«and then the component re-rendering.
â«And so this is the reason why
â«it is really not allowed to set state in render logic.
â«So let's quickly set this back here
â«so that we don't have a million requests here.
â«And so as we reload, then it stops.
â«And let's just see another example here quickly.
â«So let's say we did set watched immediately here
â«in the top level code to some empty array
â«and then actually we do get a real error.
â«I mean, let's reload that.
â«And yeah, here we are now reloading all the time again
â«the data from the API.
â«But what matters here is that
â«we get the error of too many re-renders.
â«And so that's now because of this state setting right here.
â«So if we're really setting the state here in the top level
â«even without being inside a then handler
â«then immediately React will complain
â«that there are too many renders,
â«which means that we again entered that infinite loop
â«where updating state will cause a component to re-render,
â«which will cause the state to be set
â«and so on into infinity.
â«So let's of course get rid of that.
â«Let's reload here.
â«And so now we are again good.
â«However, we do actually want to set the state here.
â«So we do want set movies here,
â«but without all the problems that we just saw.
â«And so how can we do that?
â«Well, that's where we need the use effect hook
â«which we will learn about in the next lecture.
Weitere Àhnliche Videos ansehen
useEffect to the Rescue | Lecture 140 | React.JS đ„
Rules for Render Logic: Pure Components | Lecture 131 | React.JS đ„
A First Look at Effects | Lecture 141 | React.JS đ„
The useEffect Cleanup Function | Lecture 151 | React.JS đ„
Life Cycle Methods | Mastering React: An In-Depth Zero to Hero Video Series
Introduction to Redux | Lecture 257 | React.JS đ„
5.0 / 5 (0 votes)