What is State in React?
In React, state refers to a built-in object that stores dynamic data within a component. It's like a container that holds values that can change over time and impact how the component behaves or is displayed.
Whenever the state changes, React automatically re-renders the component, ensuring the UI reflects the most up-to-date information.
In simpler terms, state is used to make React components dynamic and interactive, such as managing the user’s input in a form or updating a counter in real-time etc.,
Why Do We Need State Management?
As applications grow more complex, we deal with more dynamic data (user inputs, API responses, form values, etc.). Managing this data in an organized way is crucial to get the following benefits.
1. Keep the UI in sync with data changes.
2. Share state between multiple components when needed.
3. Avoid unnecessary re-renders by controlling which part of the app should update when data changes.
Without state management, the app can become unorganized, and we might lose control over which data impacts which part of the app, leading to bugs or unpredictable behavior.
How to create a State?
useState hook allows you to add state to a functional component.
Syntax
const [state, setState] = useState(initialValue);
1. state: The current state value (initially set to initialValue).
2. setState: A function that allows you to update the state.
3. initialValue: The initial value of the state (can be any valid data type, such as number, string, object, array, etc.).
‘useState’ function returns an array with exactly two values, first one represents the current state, and second one is a function to update that state.
How useState Works Internally?
When you call useState, React internally stores the state for the component. Each time the state changes (through the setter function like setCount), React:
1. Updates the state with the new value.
2. Re-renders the component with the new state.
3. Reuses the same state variable between renders.
Example
const [count, setCount] = useState(0);
1. count: Holds the current value of the count state (initially 0).
2. setCount: Function to update count (e.g., setCount(10) to set the count to 10).
Let’s build a counter component that perform following operations.
a. Increment the counter by 1
b. Decrement the counter by 1
c. Reset the state counter to 0.
Counter component
import { useState } from "react";
export default function Counter() {
// Initialize the count to 0
const [count, updateCount] = useState(0);
function increment() {
updateCount(count + 1);
}
function decrement() {
updateCount(count - 1);
}
function reset() {
updateCount(0);
}
return (
<div>
<h1>Count = {count} </h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}
useState Hook: In React, the useState hook is used to declare state. It returns an array with two values:
a. The current state (count in this case).
b. A function to update the state (updateCount in this case).
In this example, we initialize the state with 0 by calling useState(0).
State Changes: The functions increment, decrement and reset modify the state using updateCount. When the state is updated (e.g., updateCount(count + 1)), React re-renders the component, updating the displayed value (count) accordingly.
Event Handlers: The buttons have onClick handlers that trigger the functions, causing the state to change when the user interacts with the buttons.
Follow below step-by-step procedure to build a complete working application.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘counter-application’.
Project structure looks like below.
Step 2: Create components folder in src/ folder and define Counter Component.
Counter.jsx
import { useState } from "react";
export default function Counter() {
// Initialize the count to 0
const [count, updateCount] = useState(0);
function increment() {
updateCount(count + 1);
}
function decrement() {
updateCount(count - 1);
}
function reset() {
updateCount(0);
}
return (
<div>
<h1>Count = {count} </h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}
Step 3: Update main.jsx file like below.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import Counter from './components/Counter'
createRoot(document.getElementById('root')).render(
<StrictMode>
<Counter />
</StrictMode>,
)
Step 4: Build and run the Application by executing below commands.
cd counter-application npm install npm run dev
Open the url ‘http://localhost:5173/’ in browser, you will see below screen.
Experiment with application, by interacting with Increment, Decrement and Reset buttons.
Why can’t I update the count variable directly, instead of calling updateCount method?
In React, directly modifying state is a bad practice and won't work as expected due to how React handles state updates. Let me explain why.
If you modify the count variable directly like count = count + 1, React won't know that the state has changed, and it won't trigger a re-render of the component. React only re-renders components when the updateCount function is called because it tells React, "Hey, I've updated the state, please re-render the component with the new value."
You can download this application from this link.
Previous Next Home
No comments:
Post a Comment