- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React useState Hook
- useState is a React hook that enables functional components to manage state.
Purpose
- Allows functional components to have local state, a feature traditionally associated with class components.
- Enables dynamic updates and re-renders based on changes to state.
Syntax
- Import useState from the 'react' library.
- Use the useState function, which returns an array containing the current state and a function to update the state.
import React, { useState } from 'react';
const ExampleComponent = () => {
const [state, setState] = useState(initialState);
// state: current state value
// setState: function to update the state
};
Usage
- Initialize state with an initial value.
- Access and update state using the provided state variable and state update function.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
Handling Complex State
- For complex state objects, useState can be used with destructuring.
const [user, setUser] = useState({ name: 'Vikash', age: 25 });
// Updating a specific property
setUser(prevUser => ({ ...prevUser, age: prevUser.age + 1 }));
Functional Updates
- useState supports functional updates, useful when the new state depends on the previous state.
const [count, setCount] = useState(0);
// Using a function to update based on previous state
const increment = () => {
setCount(prevCount => prevCount + 1);
};
Multiple State Variables
- You can use multiple useState calls to manage multiple state variables independently.
const [name, setName] = useState('Vikash');
const [age, setAge] = useState(25);
Summary
useState is a versatile hook that plays a crucial role in bringing stateful behavior to functional components, contributing to the simplicity and modularity of React applications.