ReactJs Notes

 -------------------------------------- TAILWIND IN REACTJS -------------------------------------------------

Link paste in <head> tag:--
<script src="https://cdn.tailwindcss.com"></script>


Manual Intsallation for in reactjs app :--
 Use commands
1. npm create vite
2. npm i 
3. npm install tailwindcss @tailwindcss/vite


 Configure the Vite plugin 
Add the @tailwindcss/vite plugin to your Vite configuration.
import { defineConfig } from 'vite' 
import react from '@vitejs/plugin-react' 
import tailwindcss from '@tailwindcss/vite' 
// https://vite.dev/config/ 
export default defineConfig({ 
    plugins: [ 
        react(), 
        tailwindcss(), 
    ], 
})



 Import Tailwind CSS Add an @import to your CSS file that imports Tailwind CSS.
Add the @tailwind directives for each of Tailwind’s layers to your main CSS file (index.css).
@import "tailwindcss"

 use command
npm run dev


---------------------------------------------------- IMPORTANTS ---------------------------------------------------


1.๐Ÿง  useMemo hook
Firstly 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.
Secondly 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 fnuction 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

๐Ÿง  memo in React — What It Is:

memo is 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.memo

Use 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 useCallback or useMemo to stabilize those props.


๐Ÿ” Without React.memo

function Child({ name }) {
console.log("Rendering Child"); return <div>{name}</div>; }

-----> Parent re-renders → Child re-renders unnecessarily.


✅ With React.memo

const Child = React.memo(({ name }) => { console.log("Rendering Memoized Child"); return <div>{name}</div>; });

------> Now, Child only re-renders if name changes.




3. useCallback hook
useCallback 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 array
In 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-rendering
Remember 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

const memoizedCallback = useCallback(() => { // Your logic here }, [dependency1, dependency2]);

It works like useMemo, but instead of caching(storing) a value, it caches a function.


๐Ÿ” Example Without useCallback

const Parent = () => { const [count, setCount] = useState(0); const handleClick = () => { console.log("Clicked"); }; return ( <> <Child onClick={handleClick} /> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); }; const Child = React.memo(({ onClick }) => { console.log("Child rendered"); return <button onClick={onClick}>Click Me</button>; });

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

const Parent = () => { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("Clicked"); }, []); // empty deps = function reference stays the same return ( <> <Child onClick={handleClick} /> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); };

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 useEffect or 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:

AspectSide EffectsuseEffect Hook
What it isActions that affect the outside worldA React hook to handle side effects in functional components
RoleConcept — describes what happensTool — used to manage side effects in code
NatureGeneral programming behaviorSpecific to React functional components
ExamplesAPI calls, subscriptions, DOM manipulation, timersuseEffect(() => fetch(...), []), useEffect(() => {...}, [dep])
When it runsAnytime the function runs (if unmanaged)After render / on dependency change / on unmount
Control mechanismNeeds manual control (e.g., prevent repeated fetches)Built-in lifecycle control using the dependencies array
Problem if unmanagedCan cause re-renders, memory leaks, race conditionsuseEffect prevents these via cleanup functions and deps array
Used inAll 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.


import { useEffect, useState } from 'react'; function Example() { const [data, setData] = useState([]); useEffect(() => { // Side effect: Fetching data fetch('https://api.example.com/items') .then(res => res.json()) .then(setData); }, []); // Empty dependency = run only once (on mount) return <div>{data.length} items loaded.</div>; }




Comments

Popular posts from this blog

NextJS Notes

HTML NOTES