Chenyo's org-static-blog

23 Jun 2024

Weblab notes: React hooks

This is a personal note for the web.lab lectures.

1. What is a React hook

  • Special functions to access parts of the component lifestyle.
  • e.g., useState

1.1. useState is not enough

  • The output of console.log is [] instead of ["me"] because setting a state is async!
  • To do something immediately after a state is changed, use useEffect hook!

1.2. useEffect runs after specific variable change

  • useEffect(myFunction, [var1, var2]) calls myFunction everytime when var1 or var2 changes
  • useEffect(myFunction, []]) calls only once when the component is rendered for the first time (on mount)
  • useEffect(myFunction) calls at every render

2. React hook patterns

2.1. Fetch and send data

2.2. Conditional rendering

2.3. Render an array of Data

  • key is a special prop in React; it is used identify which item has changed efficiently

3. Example: Stopwatch

4. DOM and component mounting

  • DOM (Document Object Model): a programming interface for web documents; represents the structure of a document, e.g., HTML, as a tree of objects, where each object corresponds to a part of the document; it dynamically updates the document contents
    • React is a framework that manipulates DOM
  • A React component is unmounted when:
    • conditional rendering
    • routing; navigating from one route to another
    • its parent component is unmounted
Tags: study web react mit