The document discusses React hooks and how they can be used to manage state and other features in function components without writing classes. It provides examples of how common lifecycle methods and state management in classes can be re-written using hooks like useState, useEffect, and useContext. Specifically, it walks through converting a chat component that subscribes to new messages and manages local state from a class to a function component using these React hooks.
Introduction to the session on React, with a shift from discussing High-Order-Components to Hooks.
Explain React Hooks, introduced in v16.7.0-alpha, emphasizing their advantages over classes.
Presentation agenda outlines topics like Hooks Intro, useState, useRef, useContext, and others.
Introduction to useState, showcasing examples of class components vs. functional components using useState.
Explains useContext, showing how to use it without hooks and with hooks in functional components.
Introduces useRef with an example of focusing an input field, showcasing its repeated use for clarity.Describes rules of hooks and the underlying mechanics, emphasizing the order and top-level calling.
Discusses the useEffect hook, comparing it to lifecycle methods, including cleanup effects and specific scenarios.Integration of learned concepts through a chat page component with clear state management practices.
Why classes arebad?
● Complex components become hard to understand
● Classes confuse people (notorious this..)
● Classes confuse machines (don’t minify well)
● It’s hard to reuse stateful logic between classes
Rules of Hooks
●Only Call Hooks at the Top Level!
○ Don’t call Hooks inside loops, conditions, or nested functions
○ Order Matters!
● Only Call Hooks from React Functions
○ Or from custom hooks
29.
Under the hood
MyComponent
MemoizedState Array
Hooks
Dispatcher
MyComponent
- Initial Render
useState()
useRef()
useState()
State hook
Ref hook
State hook
Slot 0
Slot 1
Slot 2
30.
Under the hood
MyComponent
MemoizedState Array
Hooks
Dispatcher
useState()
useRef()
useState()
State hook
Ref hook
State hook
useState()
Search on Slot 0
MyComponent
- Initial Render
MyComponent
- 2nd Render
31.
Under the hood
MyComponent
MemoizedState Array
Hooks
Dispatcher
useState()
useRef()
useState()
State hook
Ref hook
State hook
useState()
useRef()
useState()
Search on Slot 1MyComponent
- 2nd Render
MyComponent
- Initial Render
What are CustomHooks?
● Basically functions that run hooks
● Like any other function - they can can take any args and return
whatever you want
● By convention - custom hook name start with “use”
● Like any other hook - must be called on the top level of our
components