State in React
-
This lesson introduces state in React and explains how it is used to manage and update dynamic data within components.
State is used to store data that can change over time.
In simple words:
State controls the dynamic behavior of a component.What is State?
State is:
Local to the component
Changeable
Managed inside the component
Example:
const [count, setCount] = useState(0);
When state changes, UI updates automatically.
useState Hook Introduction
useState is a React Hook used to manage state in functional components.
Syntax:
const [state, setState] = useState(initialValue);
- Example:
const [count, setCount] = useState(0);
count → current state
setCount → function to update state
Updating State
State should always be updated using the setter function.
Correct Way:
setCount(count + 1);
Incorrect Way:
count = count + 1;
Updating state triggers re-rendering.
State vs Props
Props = external data
State = internal data