React's useState hook is a powerful tool that allows functional components to manage state.
In this brief guide, we'll explore the basics of useState with simple examples to help you grasp its usage quickly.
Understanding useState
In React, state represents data that can change over time and affects a component's rendering. Before hooks, class-based components were used for state management. Hooks, including useState, simplify state handling in functional components.
Basic Syntax:
The useState hook takes an initial state value and returns an array with two elements: the current state and a function to update that state. Here's how you can use it:
const [state, setState] = useState(initialState);
Example 1: Creating a Counter
Let's create a basic counter component using useState:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
• useState(0) initializes count to 0.
• setCount is the updater function for count.
• When the "Increment" button is clicked, it calls setCount to update the state, causing a re-render with the new value.
Example 2: Managing Input Fields
Let's create a component to manage an input field's value:
import React, { useState } from 'react';
function InputField() {
const [text, setText] = useState('');
const handleInputChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input
type="text"
value={text}
onChange={handleInputChange}
placeholder="Type something..."
/>
<p>You typed: {text}</p>
</div>
);
}
• text manages the input field's value.
• setText updates text when the input changes.
• The input value is controlled by text, and changes are reflected in the paragraph below in real-time.
Top comments (0)