React Hooks

  • useState accepts a callback function that performs lazy state initialization.

    • In other words, React will only invoke that callback the first time that the component renders in order to get the initial state one time.

    • In contrast, by default, when you pass initial state, React will evaluate the initial state on every render. This evaluation can be wasteful if the initial state is computationally expensive (e.g. getting a value from local storage).

  • One compelling reason to colocate state—keep state in the component it's being used in instead of in a parent—is that state changes don't cause re-renders for the parent. This is a performance gain and so generally a good idea.

  • Derived state is state that is calculated based on other state.

  • When you're performing a lot of setState in a row, React is usually smart enough to group them into batches, so your state updates only trigger one re-render.

    • However, sometimes React can't do batch your state updates (like with async work), so you can get nasty bugs where a re-render doesn't have the data you expect.

    • To solve this, consider storing your state into 1 object: e.g. { status, blogPost } instead of status and blogPost.

    • Similarly, reducers solve the problem in the same way.

Useful Diagram for React Hooks Flow

Last updated