How to React (quickly)


At this point, our counter supports adding/removing items, but it lacks interaction with a server. Let's say that you have ordered 10 copies of a book on your phone, and you want to review your order on your laptop. We will now modify our counter to support this use case, and for that we need to learn about lifecycle methods.

Lifecycle methods

A component can implement callback functions that are called by React when particular events occur. These functions are named lifecycle methods and are called:

  • before/after the component is mounted (inserted into the DOM): componentWillMount/componentDidMount,
  • before it receives new props: componentWillReceiveProps,
  • whether the component should be re-rendered: shouldComponentUpdate,
  • before/after it is re-rendered: componentWillUpdate/componentDidUpdate),
  • and finally before the component is unmounted: componentWillUnmount.

We have already used setState to update the state of a component, the only other method from React.Component that a component might call directly is forceUpdate to force a component to update (regardless of whether its props or state have changed).

Load the initial number of items

Fix the counter-did-mount example so that it sets the count after the component is mounted.

Counter fetch

An aside note: any pending request should normally be cancelled in componentWillUnmount, unfortunately at this time this is not possible with fetch. Until abort is standardized, if you need to cancel a request when your component unmounts you will have to use XMLHttpRequest.

Create your playground on
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to
// { autofold
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
// }
class Counter extends Component {
// { autofold
constructor(props) {
this.state = {count: props.initialCount};
// }
// { autofold
handleClick(action) {
this.setState((state, props) => {
switch (action) {
case 'INCREMENT': return {count: state.count + 1}
case 'DECREMENT': return {count: state.count - 1}
// }
// TODO: use lifecycle method
async loadCount() {
let response = await fetch('/count')
let result = await response.json()
// TODO set count from result
render() {
return (
<p>Number of items: {this.state.count}</p>
{ =>
<button key={action} onClick={() => this.handleClick(action)}>
// { autofold
Counter.propTypes = {
initialCount: PropTypes.number.isRequired,
labels: PropTypes.objectOf(PropTypes.string).isRequired
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
Online Participants