Step 1 of 5 · Reading · ~2 min
Read
Reactive Foundations
Components
A component is a function that takes props and returns a vnode. That is
the entire contract.
React also has class components, with a render method and lifecycle
hooks like componentDidMount. They still work, but new code does not use
them: hooks gave plain functions everything classes had.
Props flow down, and only down
Props are read-only data handed from parent to child. A child that wants to change something calls a function its parent passed in - which is why callbacks travel as props too. Data down, events up.
The children prop
Nested content arrives as props.children, which is what lets a component
wrap markup it knows nothing about.
Render flow
- Start from the root vnode.
- Any vnode whose
typeis a function: call it with its props. - Repeat on the result, until nothing but host elements and text is left.
- Hand that flat tree to the DOM layer.
Step 2 is why a component must be pure - the renderer may call it more than once for a single visible update, and may throw a result away.
Composition, not inheritance
There is no extends in this model. A component that needs another's
behaviour renders it, or takes it as a child. React's old mixin API was
removed for exactly this reason: composition is easier to follow than an
inheritance chain you have to read upward.
Vue and Svelte package a component as a single file - template, style and logic together. React splits styling out into CSS Modules, Tailwind or CSS-in-JS. Different taste in colocation; the component model underneath is the same one you are building here.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…