Day 20: Components: What do they know? Do they know things?? Let's Find out!
Smart vs. Dumb components is a dichotomy that has dominated the React conversation as long as React has existed.
Here’s the nut: Some components know things. Some don’t.
Knowing components
Yesterday’s Pokemon app only has knowing components. They know
the id
and how to change that id
. They know when, where, and how to fetch
new data.
They know things.
Unknowing components
Unknowing components operate on props
alone. If the component works
strictly with props
, it’s an unknowing component.
const Unknowing = props => (
<div>Hi {props.name}! I didn't know you until now.</div>
)
Extracting unknowing components
Yesterday’s Pokemon
is all tangled. It knows how to fetch and
how to present.
We can untangle it by splitting Pokemon
into two components.
FetchPokemon
(knowing) keeps the smarts required to fetch a Pokemon then
gives what it knows to Pokemon
(unknowing) through props.
class FetchPokemon extends React.Component {
state = { character: null }
componentDidMount() { ... }
componentWillReceiveProps(nextProps) { ... }
render() { return <Pokemon character={this.state.character} />) }
}
Pokemon
(unknowing) has no smarts and only renders what it’s given.
const Pokemon = props =>
<div>
<h2>{props.character.name}</h2>
...
Why though?
¯\_(ツ)_/¯
This pattern alone is useless—strictly cosmetic. But—when paired with render props—it’s how you do separation of concerns in React.
Tinker with it
Use the workspace below and explore knowing and unknowing components.
- Reconstruct the coupled version of
Pokemon
. - Separate
Pokemon
andFetchPokemon
again. Practice makes perfect. - See the render prop opportunity? Take it.