React: Components as Interfaces
Why props are the public contract of a React component – and what changes when you design them like an API instead of a parameter list.
React: Components as Interfaces
A React component is not a template that someone mixed some logic into. This reading is widespread because at first glance JSX looks like a template language – and it produces exactly the components that no one wants to touch half a year later: markup with conditions sprinkled in, fifteen props without any recognizable order, and somewhere deep inside an Ajax call. A component is an interface. Props are its public contract, state is a private implementation detail, and the render result is the fulfillment of the contract. If you design props the way you design a good API – minimal, named in the language of the domain, without internals passed through – you get components that survive staff changes and fashions.
Since React 0.14, this is no longer just an interpretation; the framework itself speaks this language: a component may be a plain function that takes props and returns elements. No createClass, no class, no lifecycle – a function signature. It’s hard to express “interface” more clearly.
Props are the contract, state is a detail#
In a billing project I’m currently working on, we render a list of open invoices. The smallest unit is a row, and it is deliberately a stateless functional component:
// InvoiceRow.js - a stateless functional component (React 0.14)
const InvoiceRow = ({ invoice, isSelected, onSelect }) => (
<tr className={isSelected ? 'selected' : ''}
onClick={() => onSelect(invoice.id)}>
<td>{invoice.number}</td>
<td>{invoice.customer}</td>
<td className="amount">{formatAmount(invoice.total)}</td>
</tr>
);
From the caller’s perspective, the contract reads: give me an invoice, tell me whether it’s selected, and give me a callback for the selection. Nothing more. The component knows nothing about REST endpoints, nothing about a store, nothing about the logged-in user’s session. That’s exactly why it can be used equally in the detail view, the search results and the month-end closing – and exactly why a test can call it without a server and without browser contortions.
The counterpart of the contract is state. The official docs contain a checklist for this that I now quote almost word for word in code reviews. A value only belongs in state if all three questions are answered with no:
- Does the value come in through props?
- Does it stay unchanged over time?
- Can it be derived from other props or state values?
I’ve noticed that most React problems I see in reviews aren’t render problems but contract problems: props are copied into state on mount and drift apart afterwards, derived values are stored instead of computed, and suddenly there are two truths for the same invoice. If you consistently treat state as a private detail and express everything contractual in props, you don’t get this class of bugs in the first place.
propTypes: the contract lives in the code#
A contract that exists only in the author’s head isn’t one. React ships propTypes for this – since 0.14 directly in the react package, whether you work with React.createClass or with ES2015 classes:
InvoiceRow.propTypes = {
invoice: React.PropTypes.shape({
id: React.PropTypes.string.isRequired,
number: React.PropTypes.string.isRequired,
customer: React.PropTypes.string.isRequired,
total: React.PropTypes.number.isRequired
}).isRequired,
isSelected: React.PropTypes.bool,
onSelect: React.PropTypes.func.isRequired
};
InvoiceRow.defaultProps = {
isSelected: false
};
Technically, these are just warnings in the development environment – no compiler, no guarantee at runtime in production. Still, I consider propTypes one of the most underrated tools in the current React ecosystem, for a reason that has little to do with type checking: they are documentation that can’t go stale unnoticed. When a colleague opens InvoiceRow for the first time, she reads the contract before she sees a single line of implementation. And when someone breaks the contract, the console complains on the next development run.
Along the way, propTypes also defuse a team problem that affects many codebases right now: the coexistence of React.createClass and ES2015 classes. We write new code with Babel and classes or as stateless functions, but older parts of the application are still in the createClass style – and that will stay that way for a while, because no one rewrites a running application just over a question of syntax. As long as every component declares its contract as propTypes, that matters surprisingly little. The caller sees the same interface in both cases, and migrating a single component from one style to the other breaks nothing the contract wouldn’t report immediately.
It gets interesting when you use propTypes as a design tool instead of as a chore after the fact. In the billing project, we now write the propTypes first, before the component gets any markup. That feels cumbersome at first, but it forces the one question that matters: what does the caller really have to provide? A component whose propTypes block is longer than its render code is almost always a sign that two or three components are hiding in one.
Breaking things down as in “Thinking in React”#
With “Thinking in React,” the official docs contain a text that describes exactly this design attitude as a method – and that, in my opinion, is skipped far too often because it sounds like beginner reading. The method is simple: draw rectangles over the UI mock, give each rectangle a single responsibility, first build a static version without any state, then identify the minimal state and place it in the nearest common ancestor.
Translated into the interface view, this means: every rectangle gets a contract, and the static version is the proof that the contract holds before anything dynamic happens. The step “find the minimal state” is then not a React trick but what you also do when designing a data model – every redundancy you allow now, you have to keep in sync by hand later.
This is not a new idea. If you have ever cut a module interface or negotiated a service contract, you’ll recognize the pattern immediately. What’s new is that React makes this discipline affordable down to the smallest UI unit: a function with three props is cheap enough to throw away and re-cut if the split isn’t right.
Separating container and presentation#
The data has to come from somewhere, though. Last year, Dan Abramov wrote down the distinction between container and presentational components for this, and it quickly caught on in our project: presentational components know only their props; containers know the data source and pass results on as props.
// InvoiceListContainer.js - knows where the data comes from
class InvoiceListContainer extends React.Component {
constructor(props) {
super(props);
this.state = { invoices: [], isLoading: true, selectedId: null };
this.handleSelect = this.handleSelect.bind(this);
}
componentDidMount() {
fetchInvoices().then(invoices =>
this.setState({ invoices, isLoading: false })
);
}
handleSelect(invoiceId) {
this.setState({ selectedId: invoiceId });
}
render() {
const { invoices, isLoading, selectedId } = this.state;
if (isLoading) return <LoadingHint />;
return (
<InvoiceList
invoices={invoices}
selectedId={selectedId}
onSelect={this.handleSelect}
/>
);
}
}
The container is deliberately boring: it loads, it holds the selection state, it passes things on. InvoiceList and InvoiceRow stay pure functions of their props. The data flow can thus be read at every point – data flows down as props, events travel up as callbacks:
flowchart TD C[InvoiceListContainer<br/>State: invoices, isLoading, selectedId] -->|Props: invoices, selectedId, onSelect| L[InvoiceList] L -->|Props: invoice, isSelected, onSelect| R1[InvoiceRow] L -->|Props: invoice, isSelected, onSelect| R2[InvoiceRow] R1 -.->|onSelect with invoice.id| C
If you use Redux – and the rise of Redux is in full swing right now – you already know this pattern: connect creates nothing other than containers. But the point is independent of the library. The separation pays off even in an application without any store, because it separates the expensive components (the ones with data access) from the cheap ones (the ones with pure presentation). The cheap ones are the ones you reuse, show in the style guide and test in five minutes.
Composition via children instead of inheritance#
The second place where interface thinking becomes concrete is reuse of frames and layout. The reflex from the object-oriented world would be inheritance: a BasePanel class that special cases inherit from. In React, I haven’t needed that in a single case yet. Instead, the contract gets a placeholder – children:
// Panel.js - a layout component with a slot for arbitrary content
const Panel = ({ title, children }) => (
<div className="panel">
<h2 className="panel-title">{title}</h2>
<div className="panel-body">{children}</div>
</div>
);
// usage
<Panel title="Open invoices">
<InvoiceList invoices={invoices} selectedId={selectedId} onSelect={handleSelect} />
</Panel>
Panel knows nothing about invoices, InvoiceList knows nothing about panels. Both contracts stay minimal, and every combination is visible at the call site instead of being hidden in an inheritance hierarchy. If a panel needs several slots – say, a toolbar next to the title – that’s just another prop that takes an element. Elements are ordinary values in React, and contracts that exchange values are easier to understand than contracts that require inheritance.
The honest limit: props across many levels#
So much for the places where the interface view holds up. There is one place where it hurts at the moment, and I don’t want to hide it: props that have to be passed through many levels.
The classic example is the logged-in user. The user menu at the very bottom of the tree needs it, so it travels as a prop through components that don’t use it themselves:
flowchart LR App -->|currentUser| Page Page -->|currentUser| Toolbar Toolbar -->|currentUser| UserMenu
Page and Toolbar don’t have currentUser in their domain contract – they merely transport it. Every intermediate level that passes a foreign prop through dilutes exactly the minimality I argued for above. And in early 2016, there is no truly satisfying standard answer to this. There is relief:
- restructure the tree and use composition –
Apprenders theUserMenuitself and passes the finished element down instead of the data - place additional containers deeper in the tree that get their data themselves, with Redux for example via
connect - put application-wide data in a store as a rule and carry only local contracts via props
React does have a context mechanism meant to address exactly this problem – but the docs literally say the feature is experimental and the API is likely to be unstable. I don’t build an application that’s supposed to outlive the warning on something like that. In the project, we tolerate passing through two or three levels, restructure the tree beyond that, and rely on the store for truly global things. That’s a compromise, not a state of affairs I’m happy with. Here the ecosystem simply isn’t finished yet.
What I take away from this#
The quality of a component isn’t decided in its render code but at the call site. That’s why, in reviews, I now ask questions about the props list first, not about the implementation: do I understand the contract without opening the file? Do the names speak the language of the domain – invoice, onSelect – or the language of the technology behind it? Is there a prop in there that only exists because a deeper child needs it? Could a second, completely different caller use this component without it noticing?
Templates answer none of these questions; interfaces do. React prescribes surprisingly little for this – a function, props, children, plus propTypes as a readable contract – and exactly this sparseness is the value. The library beneath the component will keep turning; in the last year and a half alone, build tools, language standard and state libraries have turned over completely once. A cleanly cut contract of three props has a good chance of surviving all that. A template with some logic doesn’t.
Further reading#
- Thinking in React (official React documentation): react.dev/learn/thinking-in-react
- React v0.14 – release announcement with stateless functional components: legacy.reactjs.org/blog/2015/10/07/react-v0.14.html
- Dan Abramov: Presentational and Container Components (2015): medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
Revised and translated from German with the help of AI.