Lesson 6 - States

6.1 - Introduction To State

State is the fundamental concept in React that allows you to store and manage dynamic data within a component. It's the living essence that changes over time, driving reactivity and interactivity in your application.

The state is like a local variable to the component mainly used to handle data that evolves, such as user input, form data, or interactive elements that change over time.

It can be updated by the component. The component reflects the state update by re-rendering the UI.

The major difference between Props and State is that Props is used for component-to-component data sharing where State is local to a component and changes over time.

The useState hook is one of the most used states in React. It lets you add a state to the functional component. The useState hook returns an array of two elements: one is for the current state value and another is a function to update the state value.

The general syntax for the state is,

const [state, setState] = useState(initialState);

Here, the state holds the current state value, setState is a function to update the state, and initialState is the initial value of the state.

The following example demonstrates the basic use of State:

import React, { useState } from 'react';

const App = () => {
 const [num, setNum] = useState(0);

 return (
 <>
 <h1>Current Number is: {num}</h1>
 </>
 );
};

Let's dive deeper into the state and learn how to manage it.