ReactJs Notes
---------------------------------------------------- IMPORTANTS ---------------------------------------------------
1.๐ง useMemo hookFirstly lets understand what is the meaning of Memo/Memoization -> memo means is that finding the solutions and storing them at same time. ie. let suppose teacher ask a student that what is 3*4 then firstly student will calculate it then store it in his memory and whenever teacher ask the same question again then student dont need to calculate it again, he can answer it right away because the answer is already stored in his memory.
useMemo works pretty much on the same concept. useMemo hook is the way to prevent the unnessary expensive tasks/operation happening on the webapp. It stores the previous value of expensive function and prevent that function from running again and again on each re-rendering.
Let me give u an example:-
let suppose we have a page which only have 2 things one is the button which is increasing the count by 1, whenever it is getting clicked (obviously connected with useState) and another is a function which have a for loop which goes from 0 - 100000000, so whenever we click on the onClick button which increase the count then with each click the page will get re-rendered and with each re-rendering the function which have for loop will also runs... therefore it will take time to increase the value of count per clicks because of that loop is running again and again with each re-rendering.
(this is the issue we are facing)
๐งพ FLOW :-
button -> clicked -> setCount(+1) -> count update -> component re-rendering -> expensive task run -> for loop from 0 - 100000000 -> UI re-rendered and updated
NOTE: only last value for which the useMemo hook runs, only that value is stored in useMemo other value are not stored.
Syntax of useMemo hook :- const expensiveResult = useMemo(() => {
anyFunction
}, [TriggeringWhileChangingThisVariable]); -> we can have multiple values in this dependency array
❌ EXAMPLE OF CODE WITHOUT useMemo
import React, { useState } from 'react';
function WithoutUseMemo() {
const [count, setCount] = useState(0);
const [toggle, setToggle] = useState(true);
// Expensive calculation (simulated)
const expensiveCalculation = () => {
console.log("Calculating...");
let sum = 0;
for (let i = 0; i < 1e7; i++) sum += i;
return sum;
};
const result = expensiveCalculation(); // Runs on every render
return (
<div>
<h2>Without useMemo</h2>
<p>Expensive Result: {result}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<button onClick={() => setToggle(!toggle)}>Toggle</button>
</div>
);
}✅ EXAMPLE OF CODE WITH useMemo
import React, { useState, useMemo } from 'react';
function WithUseMemo() {
const [count, setCount] = useState(0);
const [toggle, setToggle] = useState(true);
const expensiveResult = useMemo(() => {
console.log("Calculating...");
let sum = 0;
for (let i = 0; i < 1e7; i++) sum += i;
return sum;
}, [count]); // only recalculates if count changes
return (
<div>
<h2>With useMemo</h2>
<p>Expensive Result: {expensiveResult}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<button onClick={() => setToggle(!toggle)}>Toggle</button>
</div>
);
}
2. memo hook๐ง
memoin React — What It Is:
memois a higher-order component (HOC) that wraps a component and memoizes it — meaning it skips re-rendering the component if its props haven’t changed.Think of it like
useMemo, but for entire components, not just values.
Syntax of memo hook:-
const MyComponent = React.memo((props) => {
return <div>{props.name}</div>;
});
⚡ When to Use
React.memoUse it when:
The component is pure (output depends only on props).
The component is re-rendering too often without need.
You're passing primitive props (strings, numbers, booleans).
⚡ Limitation
Won’t help if props are objects/functions/arrays that change on every render.
You might need
useCallbackoruseMemoto stabilize those props.
๐ Without React.memo
-----> Parent re-renders → Child re-renders unnecessarily.
✅ With React.memo
------> Now, Child only re-renders if name changes.
3. useCallback hookuseCallback is a React Hook that returns a memoized version of a callback function — which means it will not be re-created on every render unless its dependencies change. basically Its main functionality is Freezing the function, and that function can only be unfreezed when we pass the that particular state to dependency array... Its Good when we are dealing with child components and passing a expensive function as a props to child components, in that case memo don't work, so sometimes we need to use the useCallback to freeze the function
Note dependency arrays plays a crucial role in useCallback, like for freezing and unfreezing the function according to passed variables in the dependency arrayIn useMemo we stores the values in hook and it won't let that function re-running again and again (note that i am not talking about re-rendering) but in useCallback we are not stopping the re-running of function reference, instead we are stopping the recreation of expensive function reference which happened during the time of re-renderingRemember UseMemo deals with functions result value and useCallback deals with functions references...๐ก Why do we even need
useCallback?Every time a component renders, all the functions inside it get re-created. This is usually fine. But when:
You're passing functions as props to child components, and
Those child components are wrapped in
React.memo
→ Then unnecessary renders can happen just because the function reference changes.
useCallback is how you stabilize function references across renders, so children don't re-render unless they actually need to.
๐งพ Syntax
It works like useMemo, but instead of caching(storing) a value, it caches a function.
๐ Example Without useCallback
Here, even though Child is wrapped in React.memo, it still re-renders on every Parent render. Why?
Because handleClick is a new function instance every time.
✅ Example With useCallback
Now, handleClick is memoized. So unless its dependencies change (in this case, none), the same function reference is passed to Child, and Child won't re-render.
๐ When to Use useCallback
Use it when:
You're passing functions to
memoized child components.The function is used in
useEffector elsewhere where reference identity matters.You’re optimizing performance for expensive rerenders.
4. Side Effects in React๐ฅ Simple Definition:
A side effect is anything that affects something outside the component’s render scope — like fetching data, subscribing to events, updating DOM manually, or setting timers.
✅ Common Examples of Side Effects in React:
Side Effect Explanation Fetching data from an API -> External call outside the component Manually changing the DOM -> Direct DOM manipulation Setting up a subscription -> WebSocket, EventListener Timers( setTimeout,setInterval)-> Asynchronous behavior Local storage access -> External browser API Analytics/logging -> Doesn't affect render but sends data out
⚠️ Why Not Inside render()?
React expects render() (or return from a functional component) to be pure — no side effects, just return JSX based on props/state. If you do side effects there, you break React's predictable re-rendering.
Here’s a sharp and clear comparison between "Side Effects" and useEffect in React:
| Aspect | Side Effects | useEffect Hook |
|---|---|---|
| What it is | Actions that affect the outside world | A React hook to handle side effects in functional components |
| Role | Concept — describes what happens | Tool — used to manage side effects in code |
| Nature | General programming behavior | Specific to React functional components |
| Examples | API calls, subscriptions, DOM manipulation, timers | useEffect(() => fetch(...), []), useEffect(() => {...}, [dep]) |
| When it runs | Anytime the function runs (if unmanaged) | After render / on dependency change / on unmount |
| Control mechanism | Needs manual control (e.g., prevent repeated fetches) | Built-in lifecycle control using the dependencies array |
| Problem if unmanaged | Can cause re-renders, memory leaks, race conditions | useEffect prevents these via cleanup functions and deps array |
| Used in | All JS apps (conceptually) | Only inside React functional components |
⚙️ Relationship:
Side Effects = What you want to do (e.g., fetch, subscribe, log)
useEffect = Where and how you do it in React correctly
⚙️ Where to Handle Side Effects in React?
Use the useEffect hook.
Comments
Post a Comment