React Hooks and Their Rules | Lecture 157 | React.JS 🔥

The Coding Classroom
18 Dec 202310:55

Summary

TLDRReact hooks are special functions that allow developers to tap into React's internal mechanisms, such as managing state and side effects. They expose internal React functionalities and are essential for creating and accessing state in functional components. Hooks must be called in a consistent order at the top level of the component and can only be used within React functions or custom hooks. This structure ensures that React can correctly track and manage the hooks, avoiding confusion and maintaining the integrity of the application's state across renders.

Takeaways

  • 📌 React hooks are special functions that allow interaction with React's internal mechanisms.
  • 🔑 Hooks expose internal React functionality like state management and side effect registration.
  • 🌳 The fiber tree is an internal data structure in React that hooks are linked to.
  • 📈 Hooks start with 'use' to differentiate them from regular functions and for ease of identification.
  • 🛠 Custom hooks enable developers to reuse non-visual logic across different components.
  • 🎯 There are nearly 20 built-in hooks in React, with useState and useEffect being the most commonly used.
  • 📋 Hooks must be called at the top level of your code, avoiding conditionals, loops, or nested functions.
  • 🔄 Hooks rely on call order to maintain a linked list, which is crucial for React's tracking and management.
  • 🚫 Violating the call order can lead to broken references and render issues within the fiber tree.
  • 📏 The first rule of hooks ensures that the linked list of hooks remains consistent across renders.
  • 🧐 Understanding the 'why' behind React hooks and their rules helps developers write more effective and maintainable code.

Q & A

  • What are React hooks?

    -React hooks are special functions built into React that allow developers to hook into some of React's internal mechanisms, such as creating and accessing state or registering side effects.

  • What is the fiber tree in React?

    -The fiber tree is an internal data structure within React that represents the state of the UI. It is not directly accessible to developers but is used by hooks like `useState` and `useEffect` to manage state and side effects.

  • Why do all hooks start with the word 'use'?

    -All hooks start with the word 'use' to make it easy for developers and React to distinguish hooks from other regular functions.

  • What are custom hooks in React?

    -Custom hooks are developer-created functions that start with 'use' and allow for the reuse of non-visual logic, such as state management and side effects, across different components.

  • How many built-in hooks does React come with?

    -React comes with almost 20 built-in hooks, including widely used ones like `useState`, `useEffect`, `useReducer`, and `useContext`.

  • What are the two simple rules that must be followed for hooks to work as intended?

    -The two rules are: 1) Hooks can only be called at the top level in a function, not inside loops, conditions, or nested functions, and 2) Hooks can only be called from React functions, such as function components or custom hooks, not from regular functions or class components.

  • Why is it important to call hooks in the same order on every render?

    -Calling hooks in the same order ensures that React can correctly associate each hook with its value and maintain the integrity of the linked list of hooks. This is crucial for React to function properly and track state and side effects across renders.

  • What happens if you break the first rule of hooks by using them conditionally?

    -If you use hooks conditionally, the linked list of hooks can get broken between renders, causing React to become confused and unable to correctly manage state and side effects, which can lead to unexpected behavior in the application.

  • How are hooks enforced to follow the rules?

    -React's ESLint rules automatically enforce the hook rules, preventing developers from breaking them and ensuring that hooks are used correctly within the code.

  • What is the advantage of using a linked list for managing hooks?

    -A linked list allows React to associate each hook with its value based on the call order, which simplifies the process for developers as they don't have to manually assign names to each hook, reducing the potential for errors.

  • Why was the introduction of hooks a significant advancement for React?

    -The introduction of hooks allowed function-based components to have their own state and run side effects, which was previously only possible with class-based components. This made React more flexible and popular by simplifying the way state and lifecycle logic are managed.

Outlines

00:00

📚 Introduction to React Hooks

This paragraph introduces the concept of React hooks, explaining that they are special functions built into React that allow developers to access and manipulate internal React mechanisms. It emphasizes that hooks are essentially APIs that expose certain functionalities such as state management and side effects. The paragraph also highlights the ability to create custom hooks for reusing non-visual logic and contrasts the new hooks system with the older class-based components, showcasing the benefits of using hooks in functional components.

05:02

🔄 The Order of Hooks

This section delves into the importance of calling hooks in a consistent order during every render. It explains that hooks rely on a linked list structure within React's fiber tree, where each hook is linked to the next based on the order of their calls. The paragraph clarifies that conditional or nested hook calls can disrupt this list, leading to issues with state management and side effects. It emphasizes the necessity of following the first rule of hooks to ensure that hooks are always called in the same order at the top level of the component.

10:04

🔑 The Simplicity of Call Order

The final paragraph discusses the rationale behind using the call order to associate hooks with their values. It points out that this approach simplifies the process for developers by eliminating the need to manually name hooks, thus avoiding potential problems. The summary underscores the convenience and efficiency of this system, which is central to the functionality of React hooks and the underlying virtual DOM and fiber tree structures.

Mindmap

Keywords

💡React Hooks

React Hooks are special functions built into React that allow developers to 'hook into' React's internal mechanisms without writing class components. They enable the use of state and other React features in functional components. For example, the useState hook allows components to have their own state, and useEffect enables handling side effects like data fetching or subscriptions.

💡Fiber Tree

The Fiber Tree is an internal data structure used by React to manage the state of components and optimize rendering. It represents the hierarchy of React elements (or 'fibers') and includes information about the component's state, props, and the hooks used within it. The script explains that hooks rely on the fiber tree to maintain their state and order across renders.

💡useState

The useState hook is one of the most fundamental React hooks that allows functional components to have and manage their own state. It is used to store and update values that can change over time, such as user input or data fetched from an API.

💡useEffect

The useEffect hook is used in functional components to perform side effects, such as data fetching, event listeners, or any action that affects something outside the component itself. It can be thought of as an equivalent to the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components.

💡Custom Hooks

Custom Hooks are user-defined functions that start with the word 'use' and are designed to encapsulate reusable logic. They allow developers to abstract complex stateful logic and side effects, making it easier to share and reuse across different components without affecting the UI.

💡Rules of Hooks

The Rules of Hooks are guidelines that must be followed to ensure that React hooks function correctly. The first rule states that hooks must be called at the top level and not inside loops, conditions, or nested functions. The second rule is that hooks can only be called from React function components or custom hooks, not from regular JavaScript functions or class components.

💡Linked List of Hooks

A Linked List of Hooks is a data structure used by React to maintain the order and state of hooks within a component. Each hook in the list points to the next hook, creating a chain that React uses to associate hooks with their corresponding state and effects. This structure is essential for hooks to function correctly across multiple renders.

💡Component Lifecycle

The Component Lifecycle refers to the series of phases a React component goes through from its creation to its destruction. This includes mounting (initial rendering), updating (re-rendering due to state or props changes), and unmounting (destruction). Hooks like useEffect allow functional components to access and manage the lifecycle, which was traditionally only possible with class components.

💡Virtual DOM

The Virtual DOM is an abstraction of the real DOM that React uses to improve performance by minimizing direct manipulation of the actual DOM. When the state of a component changes, React creates a new Virtual DOM tree, compares it with the current tree, and calculates the changes needed to update the real DOM efficiently.

💡Re-rendering

Re-rendering is the process by which React updates the Virtual DOM and subsequently the real DOM when the state of a component or its props change. This process involves creating a new Virtual DOM tree and reconciling it with the previous one to determine the changes that need to be applied.

💡ESLint

ESLint is a static code analysis tool used to identify and report on patterns found in JavaScript code. In the context of React, it enforces the rules of hooks to ensure that they are used correctly and consistently across the codebase, preventing common mistakes that can lead to bugs.

Highlights

React hooks are special functions built into React that allow us to hook into some of React's internal mechanisms.

Hooks are APIs that expose internal React functionality, such as creating and accessing state from the fiber tree or registering side effects.

The fiber tree is a part of React that is usually not accessible, but hooks like useState and useEffect allow us to interact with it.

Hooks enable manual selection of in-store DOM nodes access context and many other things.

All hooks start with the word 'use' to distinguish them from other regular functions.

Custom hooks can be created, starting with 'use', and they allow for reusing non-visual logic in React applications.

Prior to hooks, components needed to be based on JavaScript classes to have state and access to the component life cycle.

With hooks, function-based components can have their own state and run side effects, which was a significant advancement for React.

React comes with almost 20 built-in hooks, including useState, useEffect, useReducer, and useContext.

Some hooks are less used but still important, like useRef, useCallback, and useMemo.

Hooks must be called at the top level in a component, not inside conditionals, loops, or nested functions.

Hooks must be called in the exact same order on every render to maintain the integrity of the fiber tree and associated hooks.

React's ESLint rules enforce the rules of hooks, preventing developers from breaking them inadvertently.

The linked list of hooks is crucial for React to correctly track and associate each hook with its value based on the call order.

The order of hook calls uniquely identifies each hook, eliminating the need for manual naming and associated complexities.

Understanding the internals of React hooks provides insights into the framework's workings and can help developers write more efficient code.

Transcripts

play00:01

‫We have already used a few different React hooks

play00:04

‫at this point of the course, but we have never

play00:06

‫really learned what a React hook actually is

play00:10

‫and how they work.

play00:12

‫And so let's now do that in this lecture.

play00:17

‫So React hooks are essentially special functions

play00:21

‫that are built into React and which allow us

play00:24

‫to basically hook into some of React's internal mechanisms,

play00:30

‫or in other words, hooks are basically APIs

play00:33

‫that expose some internal React functionality,

play00:37

‫such as creating and accessing state from the fiber tree,

play00:42

‫or registering side effects in the fiber tree, as well.

play00:46

‫So again, the fiber tree is somewhere deep inside React,

play00:51

‫and usually not accessible to us at all.

play00:54

‫But using the useState or the useEffect hook,

play00:57

‫we can essentially hook into that internal mechanism.

play01:02

‫Now, hooks also allow us to manually select

play01:05

‫in-store dom notes access context,

play01:08

‫and many, many other things.

play01:11

‫Now, what all hooks have in common is that they all start

play01:15

‫with the word "use," in order to make it easy for us,

play01:19

‫and for React to distinguish hooks

play01:21

‫from other regular functions.

play01:24

‫And in fact, we can even create our own so-called

play01:28

‫custom hooks, which will also start with the word "use."

play01:32

‫And this is actually one of the greatest things

play01:35

‫about hooks in general, because custom hooks

play01:38

‫give us developers an easy way of reusing non-visual logic.

play01:44

‫So logic that is not about the UI.

play01:48

‫Now, you might be aware of this or not,

play01:50

‫but there was a time when we had to use components based

play01:54

‫on JavaScript classes if we wanted to give components state

play01:58

‫and access to the component life cycle.

play02:01

‫However, this came with a few problems,

play02:04

‫which led the React team to introduce hooks.

play02:07

‫And so now with hooks, our components based

play02:11

‫on functions can have their own state,

play02:13

‫and also run side effects.

play02:16

‫And so this was a huge step forward for React,

play02:20

‫and made it even more popular than it already was.

play02:24

‫Now we only used two hooks so far,

play02:28

‫but React actually comes with almost 20 built-in hooks.

play02:32

‫And so let's get a quick overview of them here.

play02:35

‫So useState and useEffect are, of course,

play02:39

‫some of the most important hooks,

play02:41

‫and therefore the most used ones,

play02:44

‫along with useReducer and useContext,

play02:47

‫that we will actually study pretty soon.

play02:50

‫Then we have this huge list of some less used hooks,

play02:55

‫but where some of them are actually still quite important,

play03:00

‫like useRef, useCallback and useMemo.

play03:04

‫So some of these are actually worth learning,

play03:07

‫but others are a bit more obscure, I would say.

play03:11

‫And so they are not part of the curriculum of this course.

play03:15

‫And finally, there are a few hooks that are intended

play03:19

‫only for library authors.

play03:21

‫And so of course, we will also not bother looking at those.

play03:26

‫Now, in order for hooks to actually work as intended,

play03:30

‫there are two very simple rules of hooks

play03:33

‫that we must follow.

play03:35

‫The first rule is that hooks can only be called

play03:39

‫at the top level in practice.

play03:41

‫This means that we cannot call hooks inside conditionals,

play03:45

‫like if statements, and also not inside loops

play03:49

‫or functions nested inside the component.

play03:52

‫We can also not call hooks after an early return,

play03:57

‫because that's also similar to a condition.

play04:00

‫But why?

play04:01

‫Why is this such an important rule?

play04:04

‫Well, it's because hooks only work if they are always called

play04:08

‫in the exact same order, which can only be insured

play04:12

‫if we only call them at the top level.

play04:15

‫And we will look at this in more detail in the next slide.

play04:19

‫And now the second rule is actually a bit simpler.

play04:23

‫All it says is that hooks can only be called

play04:26

‫from React functions.

play04:28

‫In practice, this means that hooks can only be called

play04:32

‫from function components or from custom hooks,

play04:35

‫but not from regular functions or even class components.

play04:40

‫Now, the great news is that you actually won't have to worry

play04:44

‫about these rules at all if you're using a linter,

play04:48

‫because these two rules are automatically enforced

play04:51

‫by React's ESLint rules.

play04:54

‫So you really won't be allowed to break these rules,

play04:58

‫even if you try, like we will in the next video.

play05:01

‫So if you want, you can actually just forget about the rules

play05:06

‫and finish the video right here.

play05:08

‫But if you're curious about the deeper reason

play05:11

‫why React needs rule number one, then let's move on

play05:15

‫to the final slide of this lecture.

play05:20

‫So let's now try to answer the question of

play05:23

‫why do hooks need to be called in the same order

play05:26

‫on every render?

play05:28

‫And let's actually start from the very beginning,

play05:31

‫based on all the knowledge that we already have

play05:34

‫at this point.

play05:36

‫So remember that whenever an application is rendered,

play05:40

‫React creates a tree of React elements,

play05:43

‫also called the virtual dom.

play05:46

‫On the initial render, React also builds a fiber tree

play05:50

‫out of the virtual dom, where each element is a fiber.

play05:55

‫Now, each of these fibers contains a lot of stuff,

play05:59

‫like the received props, a list of work,

play06:02

‫and crucially for us, a linked list of all the hooks

play06:06

‫that were used in the component instance.

play06:09

‫So to understand how hooks work behind the scenes,

play06:13

‫let's build ourselves a linked list of used hooks,

play06:17

‫based on this hypothetical code example.

play06:20

‫And I say hypothetical,

play06:22

‫because this code actually doesn't work.

play06:25

‫And can you spot why that is?

play06:28

‫That's right.

play06:29

‫This code actually violates the first rule of hooks,

play06:33

‫because it conditionally defines state here.

play06:37

‫But by breaking this rule, we will understand why hooks rely

play06:41

‫on the order in which they were called.

play06:44

‫And speaking of this order, our list will be built based

play06:49

‫on the call order of the used hooks.

play06:52

‫So first this useState call, then another useState call.

play06:57

‫And then finally this useEffect call.

play07:01

‫So this is our list of hooks

play07:03

‫but it's not a linked list yet.

play07:06

‫But what does linked actually mean?

play07:09

‫Well, it means that the first list element

play07:12

‫contains a reference to the second element,

play07:15

‫which in turn, has a link to the third list element.

play07:19

‫So all the list elements are linked together,

play07:22

‫which is actually a common data structure

play07:25

‫in computer science.

play07:27

‫But anyway, moving back to our code example,

play07:30

‫let's now imagine that a re-render happened,

play07:33

‫because state A was updated from 23 to 7,

play07:38

‫but this now creates a huge problem.

play07:42

‫Notice how state B was only created initially

play07:46

‫because the condition A equaled 23 was true, right?

play07:51

‫However, after this re-render, the condition is now false,

play07:55

‫which means that this useState hook would not be called.

play07:59

‫And so state B would then no longer exist

play08:03

‫in this linked list of hooks after the render.

play08:06

‫But what the problem with that, you might ask?

play08:10

‫Well, the problem is that the first hook is still pointing

play08:14

‫to the original second hook, so to state B,

play08:18

‫but that link is now broken.

play08:21

‫So state A is now linking to a hook that no longer exists,

play08:26

‫and nothing is pointing to the effect of Z,

play08:29

‫meaning that a linked list has been destroyed.

play08:33

‫It works this way because fibers

play08:36

‫are not recreated on every render.

play08:39

‫And so this list is also not recreated.

play08:42

‫So if one of the hooks just disappears from the list,

play08:46

‫then the order of the list will get completely broken.

play08:50

‫So in conclusion, if we conditionally use the hook,

play08:54

‫like we did here, that will completely mess up the list

play08:58

‫of hooks between renders, which will leave React confused

play09:02

‫and unable to correctly track all the hooks that were used.

play09:07

‫And so this is the reason why hooks need to be called

play09:10

‫in the same order on every single render.

play09:14

‫And the only way in which we can assure that

play09:17

‫is by only calling hooks at the top level,

play09:20

‫which is exactly what the first rule of hooks says.

play09:24

‫So following this rule, the code and the list of hooks

play09:29

‫would look just like this,

play09:31

‫so without any conditionals in the code,

play09:34

‫and with the list of hooks always in the same order.

play09:38

‫Now of course, this opens up the question

play09:41

‫of why even bother having this linked list,

play09:45

‫if it requires this strange rule to exist.

play09:48

‫Well, the big reason is that a linked list,

play09:52

‫which relies on the hook call order,

play09:55

‫is the simplest way to associate each hook with its value.

play10:00

‫So basically, the order in which the hook is called

play10:03

‫uniquely identifies the hook.

play10:06

‫For example, React knows that hook number one

play10:09

‫has a state of 23, and that hook number two

play10:13

‫has a state of empty string.

play10:15

‫So the value is associated with the call order.

play10:19

‫And this is very convenient because by using the call order,

play10:23

‫we developers don't have to manually assign names

play10:26

‫to each hook, which would create multiple problems

play10:30

‫that we don't need to get into at this point.

play10:33

‫Alright, so I hope that you didn't mind

play10:36

‫yet another deep dive into some of React's internals.

play10:40

‫I personally find these really interesting and fascinating,

play10:44

‫which is why I keep getting excited

play10:47

‫to share this stuff with you.

play10:49

‫But now it's time to get back into writing some code.

Rate This

5.0 / 5 (0 votes)

Related Tags
ReactHooksFunctionalComponentsStateManagementSideEffectsFiberTreeCustomHooksHookRulesESLintJavaScriptWebDevelopment