React – States, Hooks, and useState
Web Technology
Subin Sahayam, Assistant Professor,
Department of Computer Science and Engineering
Shiv Nadar University
Front End Development Tasks
K1
This topic introduces how React manages and updates data within components.
Templates
K2
Templates
K2
React State and Lifecycle
K1
React State and Lifecycle
K2
React State and Lifecycle
Mount: Component enters the UI
Update: Component changes
Unmount: Component leaves the UI
K2
React State and Lifecycle
1. State = Component's Memory
K2
function Counter() {
const [count, setCount] = React.useState(0);
return {count}
; }
For example:
You can think: State = information that a component remembers while it is running.
For example:
React State and Lifecycle
K2
2. State is like a variable
Normally in JavaScript we can write:
let count = 0;
But React needs to know when the value changes, so that it can update the webpage.
Therefore, React provides:
const [count, setCount] = React.useState(0);
Here:
count → current value
setCount → function to change the value
0 → initial value
So useState() gives the component a special kind of variable that React can monitor.
React State and Lifecycle
K2
3. State Change → Component Re-renders
This is one of the most important concepts.
Suppose:
const [count, setCount] = React.useState(0);
Initially:
count = 0
The browser displays: Count: 0
When we do: setCount(1);
React notices:
State changed
↓
React re-renders component
↓
UI gets updated
↓
Count: 1
So: Changing state tells React: "The data has changed; update the UI."
React Hooks
K1
Hooks are built-in React functions that allow functional components to use React features such as state and lifecycle-related functionality.
React Hooks
K1
React Hooks
K1
React Hooks
K1
class Counter extends React.Component {
constructor() {
super();
this.state = { count: 0 };
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
{this.state.count}
</button>
);
}
}
with hook
function Counter() {
const [count, setCount] = React.useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
React Hooks - useState
K2
React Hooks - useState
K1
React Hooks - useState
K1
React Hooks - useState
K1
React Hooks - useState
K1
React Hooks – Online Sources
K3
Front End Development Tasks
K1
App State
K1
App State
K1
User Actions
K1
User Actions
K1
References
THANK YOU