Rules for Render Logic: Pure Components | Lecture 131 | React.JS 🔥

The Coding Classroom
5 Dec 202309:24

Summary

TLDRThis script delves into the fundamental concepts of render logic and event handler functions in React components. It emphasizes the importance of maintaining purity in render logic, adhering to functional programming principles, and avoiding side effects. The video explains how render logic describes the component's view and should always return the same output for the same input (props). In contrast, event handlers are responsible for handling user interactions, updating state, making HTTP requests, and manipulating the application. The script underscores the significance of separating these two types of logic to ensure the application's proper functioning and maintainability. It also touches upon the useEffect hook, which allows side effects to be registered and executed when the component mounts or updates.

Takeaways

  • 😃 Render logic refers to the code that participates in describing how a component's view should look like, executed when the component is rendered.
  • 😎 Event handler functions are executed as a consequence of an event they are listening to, containing code that makes things happen in the application like state updates and HTTP requests.
  • 🤔 Pure functions do not have side effects, meaning they don't depend on or modify data outside their scope, and return the same output for the same input.
  • 🚫 Side effects are interactions with the outside world, like modifying external data, making HTTP requests, or writing to the DOM.
  • ✨ React requires components to be pure functions when it comes to render logic, meaning render logic must not produce any side effects.
  • 🔒 Render logic is not allowed to mutate objects or variables outside its scope, including props and state, as it would create side effects.
  • 🔄 Updating state in render logic would create an infinite loop, which is why it's not allowed.
  • 👍 Side effects like console.log and random number generation are technically not allowed in render logic but are generally safe to use.
  • 🎯 Side effects are allowed and encouraged in event handler functions, which are not part of render logic.
  • 🔍 The useEffect hook can be used to register side effects that need to be executed when the component is first rendered.

Q & A

  • What is render logic in React?

    -Render logic is all the code that participates in describing how the view of a certain component instance should look like. It includes the code at the top level of the component function and the return block where the component returns its JSX.

  • What are event handler functions in React?

    -Event handler functions are pieces of code that are executed as a consequence of the event that the handler is listening to. They contain code that makes things happen in the application, such as state updates, HTTP requests, reading input fields, and page navigation.

  • Why is it important to differentiate between render logic and event handler functions in React?

    -It's important to differentiate between these two types of logic because they do fundamentally different things. While render logic is code that renders the component, event handlers contain code that actually changes and manipulates the application in some way.

  • What does it mean for a component to be pure when it comes to render logic in React?

    -For a component to be pure when it comes to render logic, it means that if we give a certain component instance the same props (input), then the component should always return the exact same output in the form of JSX. In other words, render logic is not allowed to produce any side effects.

  • What are side effects in functional programming?

    -A side effect happens whenever a function depends on or modifies data that is outside its scope. It can be thought of as a function's interaction with the outside world, such as mutating an outside object, making HTTP requests, writing to the DOM, or setting timers.

  • What are pure functions in functional programming?

    -Pure functions are functions without side effects. They do not change any variable outside their scope, and when given the same input, they'll always return the same output, making them predictable.

  • What are the rules for render logic in React components?

    -The main rule is that components must be pure functions when it comes to render logic. This means that render logic is not allowed to perform network requests, create timers, directly work with the DOM API, mutate objects or variables outside the component scope, or update state or refs.

  • Why can't we mutate props in React?

    -We cannot mutate props in React because doing so would be a side effect, and side effects are not allowed in render logic. This is one of the hard rules of React, as mutating props would violate the principle of components being pure functions when rendering.

  • Where are side effects allowed in React components?

    -Side effects are allowed and encouraged to be used inside event handler functions, as these are not considered render logic. Additionally, if we need to create a side effect as soon as the component function is first executed, we can register that side effect using the useEffect hook.

  • What is the next topic mentioned in the script after discussing render logic and side effects?

    -The next topic mentioned in the script after discussing render logic and side effects is state update batching.

Outlines

00:00

📘 Understanding Render Logic in React

Render logic in React components is crucial for defining how a component's view should appear. It consists of all the code at the component's top level, including JSX return blocks, and is responsible for rendering the component's appearance on the screen. Additionally, render logic can also exist within functions, such as when calling a function that contributes to the component's view, exemplified by the `createList` function in the return block. This concept underscores the distinction between render logic, which is involved in rendering components, and event handler functions, which are executed in response to user events. Event handler functions are identified by their ability to perform actions such as state updates, HTTP requests, and more, thereby fundamentally differing from render logic. The emphasis on pure components in React, influenced by functional programming principles, demands that render logic must not produce side effects, ensuring components are predictable and efficient.

05:02

🔒 Rules of Render Logic and Side Effects in React

React enforces a principle that components must act as pure functions with respect to their render logic, meaning that given the same props, a component must always render the same output without side effects. Side effects, while not inherently bad, can lead to unpredictable behavior and are restricted in the context of render logic. This includes making network requests, mutating external variables, and direct DOM manipulations, which are not allowed during rendering. However, React provides avenues for managing necessary side effects through event handlers and the `useEffect` hook for effects outside of the render logic. This structure helps maintain component purity and prevents issues like infinite loops during state updates, balancing the application's interactive capabilities with reliable rendering behavior.

Mindmap

Keywords

💡Render Logic

Render logic refers to the code that is executed when a React component is rendered. It describes how the component's view should look and consists of the code at the top level of the component function and the return block with JSX. An example from the script is: "So, render logic is basically all the code that lifts, at the top level of your component functions, and that participates in describing how the view, of a certain component instance should look like." Render logic must be pure and free of side effects.

💡Event Handler Functions

Event handler functions are pieces of code executed as a consequence of an event, such as a user interaction. They handle events like button clicks, form submissions, etc. The script provides an example: "So in our example, we have this line of code, that essentially registered handle new answer, for the change event and therefore handle new answer, is our event handle function." Event handlers are where side effects like state updates and HTTP requests can occur.

💡Side Effects

A side effect occurs when a function depends on or modifies data outside its scope, interacting with the outside world. Examples given in the script include mutating an outside object, making HTTP requests, writing to the DOM, and setting timers. Side effects are not allowed in render logic but can occur in event handler functions. The script states: "So, a side effect happens whenever a function depends, on any data that is, outside the function scope, or even more importantly, whenever a function modifies data that is outside its scope."

💡Pure Functions

Pure functions are functions without side effects. They do not change any variables outside their scope, and for the same input, they always return the same output. The script defines them as: "So basically, these are functions that do not change, any variable outside their scope. Also, when we give a pure function the same input, it'll always return the same output." Render logic in React components must be implemented as pure functions.

💡State Updates

State updates refer to modifying the state of a React component, which triggers a re-render. The script mentions: "Finally, we really cannot update state, or refs in render logic. And updating state in render logic would actually create, an infinite loop, which is why we can never do that." State updates are considered side effects and should only occur within event handler functions or lifecycle methods like useEffect.

💡Functional Programming Principles

Functional programming principles, such as avoiding side effects and using pure functions, are important in React. The script states: "Well, it's important because React requires, that components are pure when it comes to render logic, in order for everything to work as expected. But what does pure actually mean? To answer that, let's have a quick refresher, on functional programming principles, which are quite important in React in general." Following these principles helps create predictable and maintainable React components.

💡Props

Props (short for properties) are inputs passed to a React component from its parent component. The script mentions: "This means that if we give a certain component instance, the same props, so the same input, then the component should always return, the exact same output in the form of JSX." Props should be treated as immutable data and should not be mutated within the component's render logic.

💡JSX

JSX (JavaScript XML) is a syntax extension to JavaScript used in React to describe the structure of user interfaces. It allows developers to write HTML-like code directly within JavaScript files. The script refers to JSX when discussing the component's output: "So these describe exactly how the component, will be displayed on the screen. However, if we look closely, we can identify, yet another piece of render logic here, even though, this code is actually inside a function. So as you can see in the return block, the code there, is actually calling this createList function. And therefore, that logic also participates, in describing the component view."

💡useEffect Hook

The useEffect hook is a built-in React hook that allows developers to perform side effects in functional components. The script mentions: "And second, if we need to create a side effect as soon, as the component function is first executed, we can register that side effect, using a special hook called useEffect." useEffect is used for tasks like fetching data, subscribing to events, and cleaning up after the component unmounts.

💡State Update Batching

State update batching is a performance optimization technique used by React to batch multiple state updates together and perform a single re-render. The script introduces this concept at the end: "For now, let's move on to another super important topic, which is state update batching." Batching state updates can improve performance by reducing the number of unnecessary re-renders.

Highlights

Render logic is basically all the code that lifts at the top level of your component functions, and that participates in describing how the view of a certain component instance should look like.

Render logic is all the code that is executed as soon as the component is rendered.

Event handler functions are pieces of code that are executed as a consequence of the event that the handler is listening to.

While render logic is code that renders the component, event handlers contain code that actually does things, like state updates, HTTP requests, reading input fields, page navigation, and more.

React requires that components are pure when it comes to render logic, in order for everything to work as expected.

A side effect happens whenever a function depends on any data that is outside the function scope, or whenever a function modifies data that is outside its scope.

Pure functions are functions without side effects, they do not change any variable outside their scope, and when given the same input, they'll always return the same output.

Side effects are not bad in themselves, any useful program must have some interaction with the outside world.

Components must be pure functions when it comes to render logic, meaning if given the same props (input), they should always return the exact same output in the form of JSX.

Render logic is not allowed to perform network requests, create timers, directly work with the DOM API, mutate objects or variables outside its scope, mutate props, or update state or refs.

Side effects like console.log or creating random numbers are technically not allowed in render logic but can be safely used.

Side effects are only forbidden inside render logic, they are allowed and encouraged inside event handler functions.

To create a side effect as soon as the component function is first executed, we can register that side effect using the useEffect hook.

State update batching is another super important topic related to render logic and side effects in React.

Transcripts

play00:01

‫In order for the rendering process to work

play00:03

‫in the way that we just learned before,

play00:06

‫our render logic needs to follow some simple rules.

play00:10

‫So, let's look at these rules in this lecture

play00:14

‫but first of all, what actually is render logic?

play00:19

‫Well, in order to understand that,

play00:21

‫let's actually take a look at the two types

play00:23

‫of logic that we can write in React components.

play00:27

‫So, that's render logic and event handler functions.

play00:32

‫So, render logic is basically all the code that lifts

play00:36

‫at the top level of your component functions

play00:39

‫and that participates in describing how the view

play00:42

‫of a certain component instance should look like.

play00:46

‫So in this code example, there is a lot of render logic.

play00:51

‫So we have these two lines of code at a top level

play00:54

‫and then also the return block where our component returns

play00:58

‫it's JSX.

play01:00

‫So these describe exactly how the component

play01:03

‫will be displayed on the screen.

play01:06

‫However, if we look closely, we can identify

play01:09

‫yet another piece of render logic here, even though

play01:13

‫this code is actually inside a function.

play01:17

‫So as you can see in the return block, the code there

play01:21

‫is actually calling this createList function.

play01:24

‫And therefore, that logic also participates

play01:27

‫in describing the component view.

play01:30

‫And so, it's also render logic.

play01:33

‫So basically, render logic is all the code

play01:36

‫that is executed as soon as the component is rendered.

play01:41

‫So each time that the function is called.

play01:45

‫Now moving on to event handler functions,

play01:48

‫those are very easy to identify.

play01:51

‫So, they're basically pieces of code that are executed

play01:55

‫as a consequence of the event that the handler

play01:58

‫is listening to.

play02:00

‫So in our example, we have this line of code

play02:03

‫that essentially registered handle new answer

play02:07

‫for the change event and therefore handle new answer

play02:11

‫is our event handle function.

play02:14

‫And this is of course nothing new at this point.

play02:17

‫So we have done this many times in the course, right?

play02:21

‫But it's still important to differentiate

play02:24

‫between these two types of logic

play02:26

‫because they do actually do fundamentally different things.

play02:31

‫So while render logic is code that renders the component,

play02:35

‫event handlers contain code that actually does things.

play02:40

‫So basically code that makes things happen

play02:42

‫in the application.

play02:45

‫So, event handlers contain things like state updates,

play02:49

‫HTTP requests, reading input fields, page navigation,

play02:52

‫and many more.

play02:55

‫So all things that basically change

play02:57

‫and manipulate the application in some way.

play03:01

‫Now why is this all so important?

play03:04

‫Well, it's important because React requires

play03:07

‫that components are pure when it comes to render logic

play03:11

‫in order for everything to work as expected.

play03:16

‫But what does pure actually mean?

play03:19

‫To answer that, let's have a quick refresher

play03:22

‫on functional programming principles,

play03:25

‫which are quite important in React in general.

play03:29

‫And let's start with side effects.

play03:31

‫So, a side effect happens whenever a function depends

play03:36

‫on any data that is

play03:37

‫outside the function scope, or even more importantly

play03:41

‫whenever a function modifies data that is outside its scope.

play03:46

‫And I like to think as a side effect

play03:48

‫as a functions interaction with the outside world.

play03:52

‫For example, this function is mutating an outside object.

play03:57

‫And so this is clearly a side effect.

play04:00

‫Other examples of side effects are HTTP requests,

play04:04

‫riding to the DOM, setting timers and more.

play04:09

‫The other important functional concept is pure functions,

play04:13

‫which are basically functions without side effects.

play04:16

‫So basically, these are functions that do not change

play04:20

‫any variable outside their scope.

play04:23

‫Also, when we give a pure function the same input,

play04:27

‫it'll always return the same output.

play04:30

‫For example, this function is clearly a pure function

play04:34

‫because if we give it the same argument r,

play04:37

‫it'll always give us the area

play04:39

‫of the circle based on that r value.

play04:43

‫So the output only depends on the inputs,

play04:47

‫which makes this function predictable.

play04:49

‫This other function right here on the other hand

play04:52

‫is completely unpredictable

play04:55

‫because it returns a string that contains a date

play04:59

‫and that date changes every second.

play05:02

‫So in this case, even

play05:04

‫if we give the function the same input,

play05:06

‫the output will always be different

play05:08

‫because the date will always be different

play05:11

‫and therefore, this is an impure function.

play05:15

‫And the same is true for the second function.

play05:19

‫So notice how this function mutates an outside variable,

play05:22

‫which of course makes this function impure as well.

play05:27

‫Now, calling functions impure makes it sound

play05:30

‫as if side effects are somehow bad

play05:33

‫but that's actually not true.

play05:36

‫So, side effects are not bad in themselves.

play05:40

‫In fact, if we think about it,

play05:42

‫any program can only be useful if it has some interaction

play05:47

‫with the outside world at some point, right?

play05:51

‫Like a web application that never affects any data

play05:55

‫or never writes to the DOM is just completely useless.

play05:59

‫However, in order to make useful and bug-free applications,

play06:04

‫we need to know when and how to create side effects,

play06:08

‫which brings us back to React

play06:10

‫and its rules for render logic.

play06:14

‫And essentially, there's just one big rule,

play06:17

‫which is that components must be pure functions

play06:21

‫when it comes to render logic.

play06:23

‫This means that if we give a certain component instance

play06:28

‫the same props, so the same input,

play06:30

‫then the component should always return

play06:33

‫the exact same output in the form of JSX.

play06:38

‫In practice, this means that render logic

play06:40

‫is not allowed to produce any side effects.

play06:44

‫So in other words, the logic that runs

play06:47

‫at the top level and is responsible

play06:50

‫for rendering the component should have no interaction

play06:53

‫with the outside world.

play06:55

‫This means that render logic is not allowed

play06:58

‫to perform network requests to create timers

play07:01

‫or to directly work with the DOM API.

play07:05

‫For example, listening to events using at event listener.

play07:09

‫Now, according to what we learned previously,

play07:12

‫render logic must also not mutate objects

play07:15

‫or variables that are outside the scope

play07:18

‫of the component function.

play07:20

‫And this is actually the reason why we cannot mutate props,

play07:24

‫which remember is one of the hard rules of React.

play07:29

‫And so now you know why that rule exists.

play07:32

‫It's because doing so would be a side effect

play07:35

‫and side effects are not allowed.

play07:38

‫Finally, we really cannot update state

play07:42

‫or refs in render logic.

play07:44

‫And updating state in render logic would actually create

play07:48

‫an infinite loop, which is why we can never do that.

play07:52

‫State updates are technically not side effects

play07:56

‫but it's still important for them to be on this list.

play08:00

‫Now, there are other side effects that are technically

play08:03

‫not allowed as well, but that we create all the time

play08:07

‫like using console.log or creating random numbers.

play08:11

‫So these are clearly interactions with the outside world

play08:15

‫but they don't seem to do any harm.

play08:17

‫And so we can safely keep doing them.

play08:21

‫Alright, but now you might be wondering if all this stuff

play08:24

‫is not allowed, then how will I ever be able

play08:28

‫to make an API call to fetch some data?

play08:32

‫Well, keep in mind that these side effects

play08:35

‫are only forbidden inside render logic.

play08:39

‫This means that you have other options

play08:41

‫for running your side effects.

play08:43

‫First of all, we saw earlier that event handler functions

play08:47

‫are not render logic and therefore, side effects

play08:51

‫are allowed and actually encouraged

play08:54

‫to be used inside these functions.

play08:57

‫And second, if we need to create a side effect as soon

play09:01

‫as the component function is first executed,

play09:04

‫we can register that side effect

play09:06

‫using a special hook called useEffect.

play09:10

‫But we will learn all about that in the next section.

play09:14

‫For now, let's move on to another super important topic,

play09:17

‫which is state update batching.

Rate This

5.0 / 5 (0 votes)

Related Tags
ReactWeb DevelopmentFunctional ProgrammingPure FunctionsSide EffectsRender LogicEvent HandlersState ManagementTechnical ConceptsProgramming Principles