Understanding
Hooks
GenLab IB Internship Program
useState Hook
In React, useState is a hook that allows
functional components to manage local state.
Lets Try
Counter App
import React, { useState } from 'react';
Explanation:
function Counter() {
const [count, setCount] = useState(0); // Initialize state with 0 1. useState(0) initializes the count variable
const increment = () => {
setCount(count + 1); // Update state with a value of 0.
};
return (
2. setCount is used to update the state.
<div>
<h1>Count: {count}</h1> 3. React automatically re-renders the
<button onClick={increment}>Increment</button>
</div>
); component when setCount is called.
}
export default Counter;
Lets Try
Bulb ON/OFF
Explanation:
1. useState(false): Initializes the state as false, meaning the light is "OFF" initially.
2. setIsOn(!isOn): Toggles the value of isOn between true and false when the
button is clicked.
3. The UI updates dynamically to show whether the light is "ON" or "OFF."
Output:
Initially, the text says, "The light is OFF."
Clicking the button toggles the state and updates the text to "The light is ON" or
"The light is OFF," depending on the current state.
These are Basic examples
practice with more
examples to get a deep
understanding
Because
The Advanced Topics Like
useReducer
Context API
Redux Toolkit
Zustand Derived Based on
useState
Now Lets Learn
useEffect Hook
Explanation:
1. useState:
users: Stores the fetched data.
loading: Tracks whether the data is still being fetched.
2. useEffect:
Runs once when the component mounts (due to the empty dependency array []).
Fetches user data from the API.
Updates the users state with the response data and turns off the loading state.
3. Rendering:
If loading is true, it shows a "Loading..." message.
Once the data is fetched, it displays the list of user names.
Try Another Example
Thats it for
Today