State in React Component

Introduction to State in React

State in react is simply an object or other data type which allows us to manage data dynamically within the component. When the state of the component changes, the component re-renders. State can be updated by setState method in class based component. Never ever directly update or mutate state in React. If you make a direct state change, your component will not be re-rendered. In react, there are mainly two ways of creating a component:

  1. Class based component
  2. Functional based component

State in class based component

You can create a component by using an ES6 class keyword and by extending the Component class provided by React like this:

Car.js file
Car.js file

State in functional component

Prior to hooks, if you started writing a functional component and then run into a situation where you needed to add state, you would have to convert the functional component to a class component. The reason for the conversion of functional component to class component is simply because, state could only be used in class component. With the introduction of hooks in react 16.8, the state hook which we will learn in this article allows us to use state within functional component.

Counter.js file
  1. Only call Hooks at the top level: Don’t call Hooks inside loops, conditions, or nested functions.
  2. Only call Hooks from React Functions: Call them from within React functional components and not just any regular JavaScript function.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abidemi Animashaun

Abidemi Animashaun


Hi everyone! I’m a web full stack developer. I write JavaScript and Php with exemplary knowledge in Reactjs, Node.js, Laravel and Nest.js.