useState in reactjs
useState
is a hook in React that allows you to add state to functional components. It returns a state variable and a function to update that state variable. This hook is essential for managing local component state in React functional components.
Basic Usage
Example: Simple Counter
import React, { useState } from 'react';
const Counter = () => {
// Declare a state variable 'count' with an initial value of 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
};
export default Counter;
In this example:
useState(0)
declares a state variablecount
with an initial value of0
.setCount
is the function used to update the state variablecount
.
Managing Multiple State Variables
You can use multiple useState
hooks to manage different pieces of state. Example: Managing Multiple States
import React, { useState } from 'react';
const Form = () => {
const [name, setName] = useState('');
const [age, setAge] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(`Name: ${name}, Age: ${age}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="number"
placeholder="Age"
value={age}
onChange={(e) => setAge(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
};
export default Form;
In this example:
useState('')
is used to declarename
andage
state variables, both initialized with an empty string.setName
andsetAge
are functions used to updatename
andage
, respectively.
Functional Updates
When updating state based on the previous state, you can pass a function to setState
.
Example: Functional Updates
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(prevCount => prevCount + 1)}>
Increment
</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>
Decrement
</button>
</div>
);
};
export default Counter;
In this example:
setCount(prevCount => prevCount + 1)
uses the previous stateprevCount
to calculate the new state.
Initial State from a Function
If the initial state is expensive to compute, you can pass a function to useState
that returns the initial state.
Example: Initial State from Function
import React, { useState } from 'react';
const ExpensiveInitialState = () => {
const initialCount = () => {
console.log('Computing initial count');
return 10;
};
const [count, setCount] = useState(initialCount);
return (
<div>
<p>Initial count is {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
};
export default ExpensiveInitialState;
In this example:
useState(initialCount)
callsinitialCount
only once to set the initial state.
Using Objects or Arrays as State
You can use objects or arrays as state, but remember that you need to create a new object or array to update state immutably.
Example: Using Objects as State
import React, { useState } from 'react';
const UserProfile = () => {
const [user, setUser] = useState({ name: '', age: '' });
const handleChange = (e) => {
const { name, value } = e.target;
setUser((prevUser) => ({
...prevUser,
[name]: value,
}));
};
return (
<div>
<input
type="text"
name="name"
placeholder="Name"
value={user.name}
onChange={handleChange}
/>
<input
type="number"
name="age"
placeholder="Age"
value={user.age}
onChange={handleChange}
/>
<p>{`Name: ${user.name}, Age: ${user.age}`}</p>
</div>
);
};
export default UserProfile;
In this example:
setUser
uses a function to update theuser
state immutably, ensuring the state object is spread and updated correctly.
Summary
useState
Hook: Allows adding state to functional components.- Initial State: Can be set directly or using a function for expensive computations.
- Updating State: Use the state update function, either directly or with a functional update for previous state dependencies.
- Multiple States: Use multiple
useState
hooks for managing different pieces of state. - Complex State: Use objects or arrays for complex state, ensuring updates are immutable.
By leveraging useState
, you can manage component state efficiently within functional components, making your React code more concise and easier to maintain.