useMemo

Motification: cache the expesive computation executed at rendering. Note that it is still a function at rendering time, so starndard limitations, e.g., side-effect, apply

Reduce re-rendering

cache the funcational component, so that when the parent components changes but the props to the child remains same, we useMemo on the child so it does not re-render in this case. Note comparing the props is by reference only

However, if the prop has a callback function passed in, most likely, this function will be regenerated when the parent re-rendered (even with the the same params). In this case, we can put the callback in the useCallback to prevent child re-rendering

How does react render works when the state changes

When render is called, it returns a new virtual DOM. We compute which real dom is changed by diffing the virutal dom recursively (tag, data, and children properties), mark the changed node as dirty, and then render the real dom

Async-await

  • On seeing await, the control will be yielded back to the caller of await. Without await, async will run synchrounously
  • Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Context

Motiviation: share global data amount component tree nodes

If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context, but moving more complexity higher in the tree makes those higher-level components more complicated and forces the lower-level components to be more flexible than you may want.

React.createContext: When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This default value can be helpful for testing components in isolation without wrapping them.

useEffect

Common side effects

  • Mutations
  • subscriptions
  • timers
  • logging
  • async tasks. By definition, this should/does not block the browser from updating the screen

The function passed to useEffect is going to be different on every render. This is intentional. In fact, this is what lets us read the count value from inside the effect without worrying about it getting stale. Every time we re-render, we schedule a different effect, replacing the previous one.

JS keywords

  • Window.localStorage