Component Instances
There's an important concept in React that is rarely discussed: whenever we render a component in React, we create a component instance.
A lot of the information online about component instances is very, very outdated; the most popular blog post on the topic is from 2016! React has changed a ton since then, and many things mentioned in the article just aren't true anymore.
Let's dig into it.
Video Summary
Note: This video is particularly hard to summarize because it digs into two separate sandboxes. I strongly recommend watching the video, if you haven't already! It covers some very important stuff, and this summary doesn't do it justice.
- When we create a state hook, where does that state actually live? Is it associated with the React elements, or stored in a centralized place?
- The missing piece of information is called component instances.
- Whenever we render a component for the first time, we “mount” the component. Mounting a component involves two steps:
- We evaluate the returned JSX and pass it onto React, so that React can create the corresponding DOM elements.
- We create a component instance, a long-lived object that holds contextual information about this particular instance of the component.
- The state is stored on this particular instance. When we write
React.useState()
, this code "hooks into" the instance, getting and setting state from the instance. - With conditional rendering, it's possible to unmount a component. When we unmount a component, we destroy the component instance, and any stored state is lost forever.
- Component instances allow us to render multiple "copies" of the same component, and they each have their own internal state.
Here's the first sandbox from the video, the minimal React app:
Code Playground
…And here's the second sandbox from the video, the more-complex application with toggleable footer.
Code Playground