In this story, we are going to build really simple count app below with class component.
Let’s start 😀
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.
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
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
We can make code more clear through this three steps
“Don’t forget to unsubscribe”
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/