useState;
const [count, setCount] = useState(0);
count - is the variable
[count, setCount] - Array Destructuring
useState(0)- function call with arugument 0
this 0 will store in count variable , we can not able to change the variable directly so we should call the setCount function to change the variable value through the arugument.
what is the purpose of useState is , if we put normal variable like
let count = 0 ; then if there is any need to make variable dynamic through the loop, then it will not work because , here we write code in components right, we should call the function name what inside the components , first time only appear the variable value in UI , because we call only one time to render that function, so if we use useState then the component will automatically rerender when the changes will happen.
useEffect
What is a Side Effect?
import { useEffect, useState } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Count Updated");
}, [count]);
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</>
);
}
export default App;
A side effect means:
Fetching data from API
Updating DOM
Setting timers
Using local storage
Running code after rendering
Easy Real-Life Example
Imagine:
Your main job = Cooking food
While cooking:
answering phone
setting timer
opening fridge
These are not the main cooking task.
They are “side tasks”.
Similarly in React:
Rendering UI = Main work
API calls / timers = Side effects
concept
- useEffect(() => { console.log("Count Updated"); }, [count]);
React watches count
Whenever count changes, useEffect runs
2.useEffect(() => {
console.log("Count Updated");
}, []);
It will NOT run again
3.useEffect(() => {
console.log("Count Updated");
});
every rerender it will work
| Code | Runs When |
|---|---|
[count] |
When count changes |
[] |
Only once |
| No array | Every render |
StrictMode
It helps developers:
find errors
detect unsafe code
identify deprecated features
improve React applications
Top comments (0)