The same react tutorial app built in different ways.
Follows tutorial instructions in the official React docs. App-level state, mix of class and functional components.
Uses redux
and react-redux
. The state of the app lives in a single store. To change state, components emit an action object which have corresponding reducers—functions which transform the application state.
Uses React's Context API
for state management. Three methods of giving a component access to the app's context are demonstrated:
Game
uses assigns itscontextType
property to the Context object.
class Game extends React.Component {
render() {
…
<button onClick={() => this.context.toggleAscending()}>
{this.context.ascending ? 'ascending' : 'descending'}
</button>
…
}
}
Game.contextType = Context;
Board
uses a static class field to initialize itscontextType
.
class Board extends React.Component {
static contextType = Context;
render() {
…
}
}
Square
(a function component) is wrapped in aContext.Consumer
to subscribe to Context changes.
function Square({ squareId }) {
return (
<Context.Consumer>
{context => … }
</Context.Consumer>
);
}
The contextType property on a class can be assigned a Context object created by React.createContext()