2 May 2024
useState
hook is one of the fundamental hooks provided by React, enabling functional components to have a state. Before hooks were introduced in React 16.8, state management was only possible within class components. Now, with useState
, you can manage state in functional components, making them more versatile and powerful.useState
hook allows you to add state to functional components. It returns an array containing two elements: the current state value and a function to update that state. This hook can be used multiple times within a single component to manage multiple state variables.useState
works:import React, { useState } from 'react';
const Counter = () => {
// Declare a state variable 'count' and a function 'setCount' to update it
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
In this example:
useState(0)
initializes the state variable count
with a value of 0
.setCount
is a function that updates the state variable count
.import React, { useState } from 'react';
const UserProfile = () => {
const [user, setUser] = useState({
name: 'John Doe',
age: 30,
job: 'Developer'
});
return (
<div>
<h1>{user.name}</h1>
<p>Age: {user.age}</p>
<p>Job: {user.job}</p>
</div>
);
};
export default UserProfile;
const updateUser = () => {
setUser((prevState) => ({
...prevState,
age: prevState.age + 1
}));
};
const addItem = (newItem) => {
setItems((prevItems) => [...prevItems, newItem]);
};
useState
in action:import React, { useState } from 'react';
const TodoList = () => {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const addTodo = () => {
if (input.trim()) {
setTodos([...todos, input]);
setInput('');
}
};
return (
<div>
<h1>Todo List</h1>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={addTodo}>Add Todo</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
);
};
export default TodoList;
In this example:
todos
(an array of todo items) and input
(the current value of the input field).addTodo
function adds the current input value to the todos
array and clears the input field.useState
hook is a versatile and essential tool for managing state in functional React components. By understanding how to initialize, update, and manipulate state using useState
, you can build dynamic and interactive user interfaces. As you become more comfortable with useState
, you'll find that it opens up many possibilities for state management within your React applications.