What is State in ReactJs ? How to use state in Functional Components in React JS. SImple example of increment a value by using state.

Himadrikhali
2 min readMay 26, 2023

--

State

The state is an updatable structure that is used to contain data or information about the component and can change over time. The change in state can happen as a response to user action or system event. It is the heart of the react component which determines the behaviour of the component and how it will render. A state must be kept as simple as possible. It represents the component’s local state or information. It can only be accessed or modified inside the component or by the component directly.

State in functional components

As we know , it was not possible to use state in functional components because the setState() method was only supported in the class components. But with React hooks, now it is possible to use state in functional components.

The state of a component in React is a plain JavaScript object that controls the behavior of a component. The change in a state triggers component re-renders.

Two main React hooks are used to declare and manipulate the state in a function component.

  • useState
  • useReducer

The useState hook has the following syntax.

const [state, setState] = useState(intialState)

The useState hook declares a state variable that holds the state and a function (setState) that can update the state. Moreover, the state variable can be initialized by passing a value (initialState) to the useState hook.

Let’s understand with the help of an example (Functional Component).

example of useState in normal function function component

Same example (Arrow Function).

Same Example by using arrow functions

In the above code, count is declared using the useState hook with 0 as its initial value.

const [number, counting] = useState(0);

The Counter component renders two buttons in the UI, first incrementing the value of number by 1 .

In the end, the state is rendered in the UI.

<h2>{count}</h2>

--

--

Himadrikhali

As a technical trainer, I aim to provide timely updates to students on how to use new technology and troubleshoot errors to ensure a seamless experience.