React Hooks revolutionized how we write components in React by allowing us to use state and other features in functional components.
One of the most fundamental and widely used hooks is useState
. In this article, weβll break down useState
in a simple and approachable way, complete with examples using TypeScript.
What is useState? π€
useState
is a React Hook that allows you to add state to functional components. Before hooks, state management was only possible in class components.
With useState
, you can now declare and manage the state directly in functional components.
How Does It Work? βοΈ
useState
returns an array with two elements:
1- The current state value.
2- A function to update the state.
Hereβs the basic syntax:
const [state, setState] = useState(initialState);
state
: The current value of the state.
setState
: A function used to update the state.
initialState
: The initial value of the state.
A Simple Example β
Letβs start with a basic example: a counter component.
import React, { useState } from 'react';
const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};
export default Counter;
Explanation:
1- We import useState
from React.
2- We declare a state variable count
with an initial value of 0
. The type number
is explicitly specified using TypeScript.
3- We render the current value of count
and a button that updates the state when clicked using setCount
.
Using useState with Complex Types πͺπ»
useState
isnβt limited to primitive types like numbers or strings. It can also handle objects, arrays, and other complex data structures.
Letβs look at an example where we manage a user object.
import React, { useState } from 'react';
interface User {
name: string;
age: number;
email: string;
}
const UserProfile: React.FC = () => {
const [user, setUser] = useState<User>({
name: 'John Doe',
age: 25,
email: 'john.doe@example.com',
});
const updateName = () => {
setUser({ ...user, name: 'Jane Doe' });
};
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<p>Email: {user.email}</p>
<button onClick={updateName}>Change Name</button>
</div>
);
};
export default UserProfile;
Explanation:
1- We define a User interface to type the state
.
2- We initialize the state with a user
object.
3- When updating the state, we use the spread operator (...user
) to ensure we donβt lose the other properties of the object.
Handling Multiple State Variables β‘
You can use useState
multiple times in a single component to manage different pieces of state independently.
import React, { useState } from 'react';
const Form: React.FC = () => {
const [name, setName] = useState<string>('');
const [age, setAge] = useState<number>(0);
const [isEmployed, setIsEmployed] = useState<boolean>(false);
return (
<div>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="number"
placeholder="Age"
value={age}
onChange={(e) => setAge(Number(e.target.value))}
/>
<label>
<input
type="checkbox"
checked={isEmployed}
onChange={(e) => setIsEmployed(e.target.checked)}
/>
Employed
</label>
</div>
);
};
export default Form;
Explanation:
1- We use three separate useState
hooks to manage name
, age
, and isEmployed
.
2- Each state variable is updated independently based on user input.
Key Takeaways βπ»
useState
is simple yet powerful: It allows you to add state to functional components with minimal code.TypeScript enhances
useState
: By explicitly typing your state, you can catch errors early and improve code readability.You can use multiple
useState
hooks: This helps keep your state management organized and modular.
Conclusion β
useState
is the foundation of state management in functional React components.
By understanding how it works and practicing with examples, youβll be able to build dynamic and interactive applications with ease.
In the next article in this series, weβll dive into another essential hook: useEffect
. Stay tuned! π
π Connect With Me On:
π LinkedIn
π X (Twitter)
π Telegram
π Instagram
Happy Coding!
Top comments (0)