Building simple count app with class component in ReactJS

DH KIM
3 min readJan 7, 2021

--

In this story, we are going to build really simple count app below with class component.

count increased by one every second

Let’s start 😀

Create class component

Create class component by writing RCC (React Class Component) provided by VSC extension
Create class component

By writing RCC (React Class Component), you can easily create new class component.
provided by VSC extension — ES7 React/Redux/GraphQL/React-Native snippets.

Create constructor and initialize state
create constructor and initialize state (count)

If you don’t want initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.
But here, we need to use it since we want to initialize count(state) to 0.

The constructor for a React component is called before it is mounted. When implementing the constructor for a Component (React.Component) subclass, you should call super(props) before any other statement. Otherwise, you can not use this keyword in the constructor

Use componentDidMount() method

componentDidMount() is invoked immediately after a component (in this case App component) is mounted (inserted into the tree). This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

After mounted, we can increase count every 1000 ms by using setInterval

Destructoring assignment
Destructoring assignment
implicit return by wrapping object with ( )
Implicit return by wrapping object with ( )
Creating tick function that increases count by 1
Creating tick function that increases count by 1

We can make code more clear through this three steps

“Don’t forget to unsubscribe”

Unsubscribe setInterval
Unsubscribe setInterval

Count state should be increased every second only when we have App component in our page.
So we need to unsubscribe before App component will unmount.

Finally we made our simple count app with react class component.
In next story, we are change this to function component.
Thank you for reading 😍😍😍

References: https://reactjs.org/

--

--

DH KIM
DH KIM

No responses yet