Best of both worlds
Object oriented state management with functional UI components
// Do you remember these?
class CounterComponent {
state = {
count: 0,
};
increment = () => {
this.setState({
count: this.state.count + 1,
});
};
render() {
return <h1 onClick={this.increment}>Count is {this.state.count}</h1>;
}
}
// How right it felt when this was introduced?
function PureComponent(props) {
return <h1 onClick={props.increment}>Count is {props.count}</h1>;
}
// And how wrong it felt when this was introduced?
function PureComponent() {
const [count, setCount] = useState(0);
const increment = () =>
setCount({
count: count + 1,
});
return <h1 onClick={increment}>Count is {count}</h1>;
}
// What if we did not put state into pure functions, but kept classes for state...
class CounterState {
count = 0;
increment() {
this.count++;
}
}
// ...and pure components for UI?
function App({ counter }) {
return <h1 onClick={counter.increment}>Count is {counter.count}</h1>;
}
// React observing state and reconciling UI