How NOT to Fetch Data in React | Lecture 139 | React.JS 🔥

The Coding Classroom
7 Dec 202309:49

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

00:00

🔑 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.

05:01

⚠️ 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

Data fetching refers to the process of retrieving data from an external source or API. In the context of the video, data fetching is demonstrated by using the fetch API to retrieve movie data from the OMDb API. This is a crucial concept as it showcases how to integrate external data into a React application, a common requirement for most modern web applications.

💡Side Effects

Side effects are operations that interact with or modify something outside the scope of the current function. In React, side effects include data fetching, subscriptions, manually changing the DOM, and using timers. The video emphasizes that side effects should not be present in the render logic of a React component, as they can lead to unintended consequences and render issues. Instead, side effects should be handled using React's useEffect hook.

💡Render Logic

Render logic refers to the code that is executed when a React component is rendered or re-rendered. In the video, the code at the top level of the component function is considered render logic, as it runs during the initial render and subsequent re-renders. The video demonstrates that introducing side effects like data fetching in the render logic can cause issues like infinite loops and excessive re-renders.

💡State Management

State management is the process of managing and updating the state of a React component. In the video, the concept of state management is explored by attempting to update the component's state with the fetched movie data. However, updating state in the render logic leads to an infinite loop, as setting state triggers a re-render, which in turn executes the render logic again, leading to an infinite cycle of state updates and re-renders.

💡useEffect Hook

The useEffect hook is a built-in React hook that allows developers to perform side effects in functional components. It is mentioned in the video as the solution to handle side effects like data fetching correctly, without introducing issues like infinite loops or excessive re-renders. The useEffect hook allows developers to perform side effects and clean up after them, ensuring that the render logic remains pure and free of side effects.

💡API Key

An API key is a unique identifier used to authenticate and authorize access to an API. In the video, the process of obtaining an API key from the OMDb API is demonstrated. API keys are commonly required when working with third-party APIs, as they help control access, track usage, and ensure that only authorized applications can access the API's data.

💡Promises

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. In the video, the fetch API returns a Promise, which is then handled using the .then() method to access the response data. Understanding Promises is essential when working with asynchronous operations like data fetching, as they provide a structured way to handle the asynchronous flow of data.

💡Asynchronous JavaScript

Asynchronous JavaScript refers to the ability of JavaScript to handle non-blocking operations, allowing the program to continue executing without waiting for a specific task to complete. In the video, data fetching is an asynchronous operation, as the application does not need to wait for the data to be retrieved before continuing to run. The video mentions that understanding asynchronous JavaScript concepts is crucial when working with data fetching and handling Promises.

💡Infinite Loop

An infinite loop is a programming construct that repeats an operation indefinitely, without an exit condition. In the video, updating the component's state within the render logic leads to an infinite loop, as each state update triggers a re-render, which in turn updates the state again, creating an endless cycle of state updates and re-renders. This concept is used to illustrate the importance of avoiding side effects in the render logic and properly managing state updates.

💡Network Tab

The Network tab is a tool available in modern web browsers that allows developers to inspect and analyze network requests and responses. In the video, the Network tab is used to visualize the excessive fetch requests being made due to the infinite loop caused by updating state in the render logic. This tool is essential for debugging and optimizing web applications, particularly when working with network-related operations like data fetching.

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

play00:01

‫Let's now load some data

play00:02

‫into a React application for the very first time.

play00:06

‫However, in this lecture,

play00:08

‫let's start by doing it the wrong way basically,

play00:12

‫which is going to be a great learning experience.

play00:17

‫So in this section,

play00:18

‫we are going to go back to our usePopcorn application

play00:22

‫that we have been working on before.

play00:24

‫And so let's now grab the project folder

play00:27

‫and open it back up in VS code.

play00:32

‫All right, now here

play00:36

‫let's start by actually duplicating this file

play00:39

‫and then I'm gonna rename one of them to app version one.

play00:43

‫And so by doing this, we are not going to override the code

play00:47

‫that we have written before.

play00:48

‫And so you can keep it as a reference.

play00:52

‫Now, as we have learned before in the previous section,

play00:55

‫we should never update state in render logic, right?

play01:00

‫But now in this lecture, let's actually break that rule

play01:04

‫so that we can see

play01:05

‫why it actually exists in the first place.

play01:09

‫And breaking rules like this

play01:11

‫is actually a pretty great way of learning Reacts

play01:14

‫and also its rules even better.

play01:17

‫Now, the idea here is to fetch some movie data

play01:20

‫as soon as the app component here

play01:23

‫mounts for the very first time,

play01:25

‫so as soon as it has its initial render.

play01:29

‫So to fetch that data, we use the OMDb API,

play01:34

‫which is basically like an open version of IMDB.

play01:39

‫Now to get started, you need to get your own API key,

play01:42

‫which you can get for free just by clicking here

play01:46

‫and then filling out this form.

play01:48

‫And so immediately you will then get your free API key.

play01:52

‫Now then once you have that, you can just come back here

play01:55

‫to the main page so we can see how we can use this API.

play02:00

‫So our data requests should simply be sent to this URL.

play02:05

‫So just copy that.

play02:07

‫And then here, let's fetch the data using the fetch API.

play02:13

‫So using the fetch function like this.

play02:17

‫Now, right.

play02:18

‫Now, in case you're not familiar with the fetch function

play02:21

‫and on how to work with asynchronous JavaScript,

play02:24

‫then please go back to the beginning of the course

play02:27

‫and take a look at the JavaScript review section

play02:30

‫where I talk about all that in great length.

play02:34

‫But anyway here now of course

play02:36

‫you need to place your own key.

play02:38

‫And actually I want to do this,

play02:41

‫so I want to place this key in a separate variable.

play02:45

‫So let's define that out here.

play02:47

‫So key and by now, after that long previous section

play02:52

‫you know why we should actually define a variable like this

play02:56

‫outside the component function.

play02:58

‫And the reason for that is that each time

play03:00

‫the component gets re-rendered

play03:02

‫this entire function here will be executed again.

play03:05

‫So basically all the render logic.

play03:08

‫And so if this variable definition here

play03:10

‫is part of that render logic

play03:12

‫it'll also be recreated each time data component renders,

play03:16

‫which is in this case, of course, not a big deal

play03:20

‫but it's good to already get

play03:22

‫into the habit of not doing that.

play03:24

‫So when you're just defining a variable like this

play03:27

‫that doesn't depend on anything that's inside the component,

play03:31

‫then just declare it outside.

play03:34

‫Now I'm just getting my own API key,

play03:37

‫but of course you should use your own one here.

play03:41

‫And now let's go back to the documentation page

play03:44

‫where we can see that we can query the API in two ways.

play03:48

‫So we can search for an ID or a title

play03:51

‫or we can actually search by some query string.

play03:55

‫And so that's actually what we will do here.

play03:59

‫So here let's use S and then equal.

play04:03

‫And then here you can type your favorite movie,

play04:05

‫which for me probably is "Interstellar".

play04:08

‫Not 100% sure of that, but it's definitely a great one.

play04:14

‫Okay.

play04:15

‫But anyway, now we need to handle the promise

play04:20

‫that the fetch function here returns inside.

play04:23

‫And of course here it's then, so inside a then method,

play04:27

‫which gets access to the response

play04:30

‫and then here we can convert that response

play04:33

‫to Json immediately, which will return another promise.

play04:40

‫And so we chain on another then

play04:42

‫and then here we get access to the data,

play04:46

‫which we can then for now log to the console.

play04:50

‫And for now, that's actually it.

play04:53

‫So let's see what we get here.

play04:56

‫Or of course we first need to

play04:57

‫actually start our application.

play05:00

‫So make sure you are in the right project folder here

play05:04

‫and then type npm start.

play05:07

‫So that should then open up the new tab here.

play05:10

‫And indeed, there it is.

play05:13

‫So let's check out our console

play05:17

‫and let's just reload quickly.

play05:18

‫And indeed you see that React was able

play05:21

‫to fetch the data from the API.

play05:24

‫So we are just interested in the search here.

play05:27

‫And so all the movies here are in fact about "Interstellar",

play05:31

‫which means that our query here is already working.

play05:34

‫Now as we learned in the previous section,

play05:37

‫this data fetching that we're doing right here is actually

play05:40

‫introducing a side effect into the component's render logic.

play05:45

‫So it is clearly an interaction with the outside world,

play05:48

‫which should never be allowed in render logic.

play05:52

‫So again, all this code that is here

play05:54

‫at the top level of the function is of course

play05:57

‫code that will run as the component first mounts

play06:00

‫and therefore it is called render logic.

play06:03

‫And so again, here we should have no side effects.

play06:07

‫I mean, in this example

play06:08

‫where we only log something to the console,

play06:11

‫it actually appears to work just fine,

play06:13

‫but watch what happens if we set some state here.

play06:17

‫And to do that

play06:18

‫let's actually first get rid of our temporary data here.

play06:23

‫So this movie data and watched data

play06:26

‫we only used as a template for the previous section,

play06:31

‫but now let's get rid of that.

play06:33

‫And so as I was just saying,

play06:35

‫let's now here actually set state.

play06:39

‫So that list of movies that we get from the API

play06:42

‫we now want to get it into our movie state.

play06:46

‫And so that's at data.search.

play06:49

‫Give it a save and beautiful.

play06:53

‫So we got some data from the API now showing up in our UI,

play06:58

‫but watch what happens when we check out the network tab.

play07:04

‫So you see that it's basically running

play07:06

‫an infinite number of requests here, so it keeps going

play07:10

‫and it never really stops.

play07:13

‫So every second our app is firing off

play07:15

‫multiple fetch requests to this API,

play07:18

‫which of course is a really, really bad idea.

play07:22

‫So why do you think that is?

play07:24

‫Why do you think all these fetch requests

play07:26

‫are being fired off?

play07:28

‫Well, the reason is that setting the state here

play07:31

‫in the render logic will then immediately

play07:33

‫cause the component to re-render itself again.

play07:37

‫So that's just how state works, right?

play07:40

‫However, as the component is re-rendered,

play07:43

‫the function here of course is executed again,

play07:46

‫which then will fetch again,

play07:48

‫which in turn will set the movies again as well.

play07:51

‫And then this whole thing starts over and over again.

play07:55

‫So as the state instead the component is re-rendered again,

play07:59

‫which then will fetch again,

play08:00

‫which will set the movies again.

play08:02

‫And so this really is an infinite loop of state setting

play08:06

‫and then the component re-rendering.

play08:08

‫And so this is the reason why

play08:10

‫it is really not allowed to set state in render logic.

play08:15

‫So let's quickly set this back here

play08:18

‫so that we don't have a million requests here.

play08:22

‫And so as we reload, then it stops.

play08:26

‫And let's just see another example here quickly.

play08:29

‫So let's say we did set watched immediately here

play08:33

‫in the top level code to some empty array

play08:37

‫and then actually we do get a real error.

play08:41

‫I mean, let's reload that.

play08:45

‫And yeah, here we are now reloading all the time again

play08:49

‫the data from the API.

play08:51

‫But what matters here is that

play08:52

‫we get the error of too many re-renders.

play08:55

‫And so that's now because of this state setting right here.

play08:59

‫So if we're really setting the state here in the top level

play09:02

‫even without being inside a then handler

play09:05

‫then immediately React will complain

play09:07

‫that there are too many renders,

play09:09

‫which means that we again entered that infinite loop

play09:12

‫where updating state will cause a component to re-render,

play09:16

‫which will cause the state to be set

play09:18

‫and so on into infinity.

play09:21

‫So let's of course get rid of that.

play09:24

‫Let's reload here.

play09:25

‫And so now we are again good.

play09:28

‫However, we do actually want to set the state here.

play09:32

‫So we do want set movies here,

play09:34

‫but without all the problems that we just saw.

play09:37

‫And so how can we do that?

play09:40

‫Well, that's where we need the use effect hook

play09:43

‫which we will learn about in the next lecture.

Rate This

5.0 / 5 (0 votes)

Related Tags
ReactData FetchinguseEffectState ManagementWeb DevelopmentJavaScriptProgramming TutorialBest PracticesInfinite LoopLearning Experience