📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Motivations for Hooks
  • useState
  • useEffect
  • Skipping effects
  • Hooks Best Practices
  • Custom Hooks
  1. Other
  2. Random Notes

Understanding React Hooks

Motivations for Hooks

There were 3 main considerations for introducing React hooks:

  1. Adding reusable stateful logic to a component with ease

    • Patterns like higher-order components allow us to inject common stateful logic between components, but it leads to wrapper hell

    • React hooks give us a primitive for sharing stateful logic

  2. Keeping mutually related code together

    • Mutually related code (e.g. code related to an API fetch) gets broken up and placed into different lifecycle methods

    • As components get more complex, you end up with unrelated code side by side and related code far and away from each other

    • React hooks let you organize your code based on what pieces are related rather than forcing a split based on lifecycle methods

  3. Classes bring unnecessary complexity

    • Classes are confusing, especially because of this

    • Also, classes run into some optimization issues, which we want to dig ourselves out of before it becomes a real issue

    • React hooks give us all of React's core features without the need for a class

useState

Note: When you setState via useState, the state variable gets replaced, not merged or updated. That means objects and arrays won't have the same references; they're brand new. (In contrast, this.setState merges values into a this.state object.)

const [list, setList] = useState([1,2,3])

setList([4,5,6]) // <= REPLACES [1,2,3]

Best practice: Because you can use as many useState calls as you want and you can use objects and arrays as state, it's best to create unique state variables based on which values tend to change together. This helps with separation of concerns.

useEffect

useEffect has the following basic structure:

useEffect(() => { // <= Callback function that gets called *after* every render
  console.log('useEffect ran')

  return () => { // <= Cleanup function that gets called *before* every effect (but not first effect after first render)
    console.log('Cleanup for useEffect ran')
  }
})

Note: When a component unmounts in the above case, the cleanup function will run because it's before a potential re-render. However, the actual effect function won't run because an unmount doesn't count as a re-render.

Other things to know about useEffect:

  • Every useEffect runs in the order in which they're invoked in your functional component.

  • The effect function and cleanup function will run around every render. This leads to fewer bugs and cleaner code because it ensures consistent cleanup.

    • In contrast, class components have to use componentDidUpdate to perform the cleanup consistently.

Skipping effects

Sometimes, for performance reasons, you don't want to apply the effect after every render. Instead, you only want to apply the effect when a specific value changes.

Class components do this by comparing prevProps or prevState to this.props and this.state respectively:

componentDidUpdate(prevProps, prevState) {
  if (prevState.count !== this.state.count) {
    // Perform effects conditionally
  }
}

useEffect does this by passing a dependency array:

useEffect(() => {
  // Perform effects conditionally
}, [count])

React will compare the current value of count to its previous value. If there's a difference, the effect is applied.

More about dependency array:

  • Make sure you pass every props, state, and any values derived from them that are used in useEffect.

    • Pro tip: When invoking a function, it's easier to see your dependencies if you define that function inside useEffect. This also means NOT having to include the function as a dependency.

    • It's only okay to omit a function from your dependency array if nothing in it uses props, state, and values derived from them.

    • Alternative: You can also use useCallback to ensure the function doesn't become stale.

  • If the dependency array has multiple values, the effect will run if even just ONE value changes.

  • Important: If you pass [] as the dependency array, the effect and cleanup functions will behave like componentDidMount and componentWillUnmount.

Hooks Best Practices

Always call a hook at the top level of a functional component; never inside nested functions, conditional flows, or loops. This ensures that your hooks are always called in the same order during a re-render.

Why: React is only able to remember state across re-renders because it stores it in an array. If you include things like conditional logic, hooks won't always be in the same order, throwing everything off. Example:

const [count, setCount] = useState(0)

if (count === 0) { // <= The second useState runs only on first render!
  setCount(count + 1)
  const [secondState, setSecondState] = useState(null)
}

const [thirdState, setThirdState] = useState(null) // <= THIS BREAKS on re-render because its position has shifted!

The only exception is custom hooks, where you can use a React hook inside!

Custom Hooks

PreviousRandom NotesNextPython

Last updated 3 years ago

Custom hooks are an alternative to and in that they allow you to create custom reusable stateful logic.

higher-order components
render props