Author: M Abo Bakar Aslam
useState Hook
26:09Before continuing this lesson, you can download the starting code using the links below. This will help you run and understand all examples easily.
useState is used to define variables in the React environment. Unlike normal JavaScript variables, state variables allow React to update the User-interfaces (UI) whenever their value changes.
Example 1: Create a variable and display its value on a webpage.
-
Line 4: variable is declared and defined
-
Line 7: The variable is called to display its values by using curly braces
{ }
// File: App.tsx located in app-name/src/
export default function App() {
let variableX = 100;
return (
<div>
<h1>Value of simple variable in JavaScript: {variableX}</h1>
</div>
);
}Example 2: Create a button having onClick attribute on it in which you will try to update the value of the variable.
Problem: When a variable is updated using a function (e.g., button click), the updated value is not reflected on the UI.
Reason:
React does not track normal variables for changes, so it does not re-render the component.
-
Line 5-8: The defined function will be called when clicking the button. In this function, we update the value of the variable. Moreover, a string will be displayed whenever the function is called.
-
Line 12-17: button is created with onClick attribute in which above function is called.
Note: When you click on the button then the function will be called (verify in the console window of the browser), but the value of the variable will not be changed. Because we will have to use useState to update the value.
// File: App.tsx located in app-name/src/
export default function App() {
let variableX = 100;
const changeValue = () => {
console.log("Function is called...");
variableX = 200;
};
return (
<div>
<h1>Value of simple variable in JavaScript: {variableX}</h1>
<button
onClick={changeValue}
style={{backgroundColor: "black", color: "white", padding: "5px"}}
>
Change value
</button>
</div>
);
}Example 3: Solve error of example-2 by using useState Hook.
Create state-variable for integral data.
Key Concepts
- Line 3: import useState from react
- Line 7: declare state-variable (state_variableX), its updating function (set_variableX) and initialized value (0).
- Line 11: update value (i.e., 500) of state-variable by using its function.
- Line 15: Display updated value of simple variable. But it is not updated, although the function is called and values is updated.
- Line 16: Displaying state-variable.
// File: App.tsx located in app-name/src/
import { useState } from "react";
export default function App() {
let variableX = 100;
const [state_variableX, set_variableX] = useState(0);
const changeValue = () => {
console.log("Function is called...");
variableX = 200;
set_variableX(500);
};
return (
<div>
<h1>Value of simple variable in JavaScript: {variableX}</h1>
<h1>Value of state for variable {state_variableX}</h1>
<button
onClick={changeValue}
style={{backgroundColor: "black", color: "white", padding: "5px"}}
>
Change value
</button>
</div>
);
}Example 4: Create state-variable for string data.
- Line 8: declare state-variable for string (state_stringVariable), its updating function (set_stringVariable) and initialized value (initial values).
- Line 13: update value (i.e., New Value) of state-variable by using its function.
- Line 22: Displaying state-variable.
// File: App.tsx located in app-name/src/
import { useState } from "react";
export default function App() {
let variableX = 100;
const [state_variableX, set_variableX] = useState(0);
const [state_stringVariable, set_stringVariable] = useState("initial values");
const changeValue = () => {
console.log("Function is called...");
variableX = 200;
set_variableX(500);
set_stringVariable("New Value");
};
return (
<div>
<h1>Value of simple variable in JavaScript: {variableX}</h1>
<h1>
<b>Value of state for variable: </b> {state_variableX}
</h1>
<h1>
<b>String State Variable: </b> {state_stringVariable}
</h1>
<button
onClick={changeValue}
style={{backgroundColor: "black", color: "white", padding: "5px"}}
>
Change value
</button>
</div>
);
}Example 5: Create state-variable for array data and display by with and without map( ) function.
Displaying Array
- Direct display shows values in a simple format
- Using
map()allows structured display of each element
Important Concept
map()is commonly used to iterate over arrays in React- Each element should have a unique key
- Line 11: define state-variable for array type data (i.e., state_array_color). It has some initial values.
- Line 38: Display without map ( ) function.
- Line 43-53: use map( ) function to display array type state-variable (state_array_color).
// File: App.tsx located in app-name/src/
import { useState } from "react";
export default function App() {
let variableX = 100;
const [state_variableX, set_variableX] = useState(0);
const [state_stringVariable, set_stringVariable] = useState("initial values");
//array type states
const [state_array_color, set_array_color] = useState(["red", "yellow", "green"]);
const changeValue = () => {
console.log("Function is called...");
variableX = 200;
set_variableX(500);
set_stringVariable("New Value");
};
return (
<div>
<h1>Value of simple variable in JavaScript: {variableX}</h1>
<h1>
<b>Value of state for variable: </b> {state_variableX}
</h1>
<h1>
<b>String State Variable: </b> {state_stringVariable}
</h1>
<button
onClick={changeValue}
style={{backgroundColor: "black", color: "white", padding: "5px"}}
>
Change value
</button>
{/* Display in array */}
<p>
<b>Color Array Data: </b>
{state_array_color}
</p>
{/* Using map() function to display array*/}
<ul>
{
state_array_color.map((elem, index) => {
return (
<li key={index}>
Index {index}: {elem}
</li>
);
}
)
}
</ul>
</div>
);
}Example 6: Updating Array State
To update an array in React:
- Do not modify the original array directly
- Create a new array and update state using spread operator
Key Idea
React detects changes only when a new reference is created. Therefore, always create a new array when updating state.
// File: App.tsx located in app-name/src/
import { useState } from "react";
export default function App() {
let variableX = 100;
const [state_variableX, set_variableX] = useState(0);
const [state_stringVariable, set_stringVariable] = useState("initial values");
//array type states
const [state_array_color, set_array_color] = useState(["red", "yellow", "green"]);
const changeValue = () => {
console.log("Function is called...");
variableX = 200;
set_variableX(500);
set_stringVariable("New Value");
};
const updateArray = () =>{
state_array_color.push("Magenta");
set_array_color([...state_array_color]);
}
return (
<div>
<h1>Value of simple variable in JavaScript: {variableX}</h1>
<h1>
<b>Value of state for variable: </b> {state_variableX}
</h1>
<h1>
<b>String State Variable: </b> {state_stringVariable}
</h1>
<button
onClick={changeValue}
style={{backgroundColor: "black", color: "white", padding: "5px"}}
>
Change value
</button>
{/* Display in array */}
<p>
<b>Color Array Data: </b>
{state_array_color}
</p>
{/* Using map() function to display array*/}
<ul>
{state_array_color.map((elem, index) => {
return (
<li key={index}>
Index {index}: {elem}
</li>
);
})}
</ul>
{/* Button to update Array */}
<button style={{backgroundColor: "black", color: "white"}} onClick={updateArray}>Add "Magenta" in Array</button>
</div>
);
}Example 7: Decrement and Increment by Clicking on respective buttons.
State variables are commonly used for counters.
You can:
- Increase value using increment button
- Decrease value using decrement button
Each click updates the state and re-renders the UI automatically.
// File: App.tsx located in app-name/src/
import { useState } from "react";
export default function App() {
const [count, setcount] = useState(0);
const [decCount, setdecCount] = useState(100);
const inc = ()=>{
setcount(count + 1);
}
const dec = ()=>{
setdecCount(decCount - 1);
}
return (
<div>
<h1>{count}</h1>
<button onClick={inc}>+</button>
<br />
<h1>{decCount}</h1>
<button onClick={dec}>-</button>
</div>
);
}Important Notes
- Always use useState for dynamic data
- Avoid direct mutation of state
- Use setter function to update state
- State changes trigger re-rendering
Best Practices
- Use meaningful state variable names
- Keep state minimal and relevant
- Avoid unnecessary state variables
- Use array methods like map, filter properly