The useState
hook is a fundamental hook in React that allows functional components to have state. It provides a way to add state variables to functional components, enabling them to manage and update their own state. In this blog post, we'll explore the useState
hook in detail with different examples.
Basic Usage
The basic syntax of useState
is:
const [state, setState] = useState(initialState);
Where state
is the current state value, setState
is a function used to update the state, and initialState
is the initial value of the state variable.
Example 1: Counter
Let's start with a simple example of a counter:
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>
);
}
Example 2: Toggle
Here's an example of a toggle button:
import React, { useState } from 'react';
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<div>
<p>The light is {isOn ? 'on' : 'off'}</p>
<button onClick={() => setIsOn(!isOn)>Toggle</button>
</div>
);
}
Example 3: Input Field
Here's an example of an input field:
import React, { useState } from 'react';
function InputField() {
const [value, setValue] = useState('');
return (
<div>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<p>You typed: {value}</p>
</div>
);
}
Conclusion
The useState
hook is a powerful tool for managing state in functional components. Whether you're building a counter, implementing toggles, or handling form inputs, useState
provides a simple and efficient way to add stateful behavior to your React components.
Experiment with different use cases and explore the flexibility of useState
to enhance the functionality and interactivity of your React applications!