ReactJS introduced Hooks to give functional components the ability to manage state and side effects β which was previously only possible in class components. The most commonly used hook is useState, which lets you create and update state variables directly inside your functional components. In simple words, state allows your React component to “remember” values between renders β such as form inputs, button clicks, counters, etc.
In this article, weβll explore how to use the useState hook to build a simple counter app. You will learn how to define a state variable, update its value using the setter function, and reflect those changes in the UI. This is one of the most essential building blocks for any modern React application.
Letβs dive into the code and see how it works step-by-step.
β Example: Counter Using useState in React Functional Component
π§© HTML + JavaScript (ReactJS Functional Component)
import React, { useState } FROM 'react';
FUNCTION CounterApp() {
// Step 1: DECLARE state USING useState hook
const [COUNT, setCount] = useState(0);
// Step 2: CREATE handler TO UPDATE state
const increase = () => {
setCount(COUNT + 1);
};RETURN (
<div STYLE={{ padding: '20px', fontFamily: 'Arial' }}>
<h2>ReactJS Counter USING useState</h2>
<p>CURRENT COUNT: <strong>{COUNT}</strong></p>
<button onClick={increase} STYLE={{ padding: '10px 20px' }}>
Increase COUNT</button>
</div>
);}export DEFAULT CounterApp;
π‘ Key Concepts:
- useState(0) initializes the count state with 0
- setCount updates the state value
- Re-render occurs whenever state is updated
- You can have multiple useState() calls for different values
How do you use the useState hook to manage state in a functional component?
import React, { useState } from react; Within your functional component, call useState with the initial state value as an argument. It returns an array containing two elements: The Current state value: Use this in your JSX to display the data dynamically.
Which state Hooks can be used to maintain state in functional components?
The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.
How do you initialize state in a functional component using Hooks?
You can achieve this by passing an argument called initialState to the useState hook within your custom hook. The second requirement is to expose a reset function handler to the consumer. You can achieve this by returning a reset function from your custom hook that resets the state to the initial state.
Related Topics | You May Also Like
|
π Get Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β |