1/1/1970
Resources
More on Props Understanding Props in ReactJS
More on State Hook React useState Hook - React Hooks Explained (Piyush Garg)
useEffect is a React Hook that lets you handle side effects in functional components.componentDidMount, componentDidUpdate, and componentWillUnmount in class components.Basic Syntax :
// App.js
useEffect(()=>){
// Effect logic here
return ()=>{ // Return Logic}
},[])Import:
// App.jsx
import {useEffect} from 'react'Run on Every Render (i.e. anything render anytime)
useEffect(() => {
alert("I run on every render!"); // alert everytime something render
});Run only on first render (i.e. whenever the component itself loaded/reloaded)
useEffect(()=>){
alert("Hello, This is the first render of App.jsx") // alert everytime component load/reload
},[])Run whenever a particular state (count) is changed, rendered or reloaded :
const [count, setCount] = useState(0);
useEffect(() => {
alert("Count was changed"); // Alert every time the count changes (even on the first display)
}, [count]);Run whenever a particular prop (color) is changed, rendered or reloaded :
// Nav.js
import { useEffect } from 'react';
const Navbar = ({ color }) => {
useEffect(() => {
alert("Color was changed"); // Alert every time the color prop changes (passed via `App.js`)
}, [color]);
return (
<div>
Hello, the color is {color}.
</div>
);
};// App.js
import Navbar from './Nav.js';
return (
...
<Navbar color={"navy" + "blue"} />
...
);Run on Every render:
// Nav.js
import { useEffect } from 'react';
const Navbar = ({ color }) => {
useEffect(() => {
alert("I run on every render"); // Alert every time something renders (e.g., color change and re-render)
});
// note: color must be rerender (one way was to make color state and use setColor)
return (
<div>
Hello, the color is {color}.
</div>
);
};Render when the component (Navbar) is mounted and return when it is unmounted:
// Nav.jsx
useEffect(() => {
alert("Hello, Welcome to my page."); // Runs when the component is rendered (mounted)
return () => {
alert("Component was unmounted"); // Runs when the component is unmounted
};
}, []);Dependency Behavior
useEffect(() => { ... }) : Runs on every render of the component (initial render + every update).useEffect(() => { ... }, []) : Runs only once, after the component's initial render (like componentDidMount).useEffect(() => { ... }, [value1, value2]) : Runs only when specified dependencies (value1, value2) or Prop change.
value++ (increment/decrement operations).setValue(newValue) (state update).value = newValue (direct assignment).Note:
The return inside useEffect is called the cleanup function, executed:
In Vite, .jsx files are required for JSX syntax. Use .jsx instead of .js to avoid errors.
Strict Mode Behavior
<React.StrictMode> causes useEffect to run twice on the initial render.Best Practices
useEffect for side effects only (e.g., data fetching, event listeners, or DOM updates).useEffect, as it can lead to infinite loops.More on Effect Hook React useEffect Hook(Piyush Garg)
React Context provides a way to share data (like state, functions, or themes) across components without passing props through every level of the component tree (avoids prop drilling).
Prop Drilling: passing data from a parent component to a deeply nested child component by passing it as props through intermediate components, even if those intermediate components don't directly use the data.
Let there is a counter count, and we want this count value inside a component Component1.js
App.jsx
⬊
Navbar.jsx
⬊
Button.jsx
⬊
Component1.jsx
We can achieve this by prop drilling, by transferring prop count from app to Navbar then to Button and then finally to Component.
But this is not a good approach, as we are passing a value from one component to others, even it is not required.
// src/App.jsx
const [count, setCount] = useState(0);
const App = () =>{ return( <Navbar count={count}/> }
// src/components/Navbar.jsx
const Navbar = ({count}) =>{ return( <Button count={count}/>) }
// src/components/Button.jsx
const Button = ({count}) =>{ return( <Component count={count}/>) }
// src/components/Component1.jsx
const Component1 = ({count}) =>{ return(<div> {count} </div>) }count in Component1 (Read-Only)Create Context
// src/context/context.js
// import `create` context hook
import {createContext} from "react";
// create and export a `context` variable
export const counterContext = createContext(0)Provide Context in App.jsx
// import the defined counter Context
import {counterContext} from './context/context'
const [count, setCount] = useState(0)
function App(){
return(
// wrap the component inside context Provider
<>
<counterContext.Provider value={count}>
<Navbar/>
</counterContext>
</>
)
}Consume Context in Component1.jsx
// import `use` Context Hook
import {useContext} from 'react'
const Component1 = () =>{
// use the context created inside `context.js` through `useContext`
const counter = useContext(counterContext)
return (
<div>
{counter} {/*Count Value */}
</div>
)
}count from Button and Display in Component1Provide count and setCount in App.jsx
// App.jsx
...
return(
<counterContext.Provider value={{count, setCount}}>
</counterContext.Provider>
)
...Consume count and Display in Component1.jsx
// Component1.jsx
const Component1 = () =>{
const value = useContext(counterContext)
return (
<div>
{value.counter} {/*count value*/}
</div>
)
}Consume setCount and Update count from Button.jsx
// Button.jsx
const Button = () =>{
const value = useContext(counterContext)
return(
<div>
<button onClick={()=>value.setCount((count)=>count+1)}> {/*setCount function*/}
</button>
</div>
)
}Key Note:
createContext to define a shared context. Export it to be used in other components.<Context.Provider> to supply the context value. All descendants can consume the value.useContext hook to access context values in a component.Benefit:
Limitations:
Note:
context file there is no need to make it jsx)<context-Name>.Provider and there Descendent will be provide the value inside <context-Name>.ProviderMore on Context HOOK React Context API in One Video | ReactJS | ReactJS Tutorial In Hindi(Piyush Garg)
Import:
// App.jsx
import {useRef} from 'react'Consider a counter button:
const [count, setCount] = useState(0);
useEffect(() => {
console.log("re-rendering...");
});setCount updates count by +1, causing the component to re-render."re-rendering..." is logged on every render.Now, introduce a variable a that increments on every render and logs its value:
let a = 0;
useEffect(() => {
a = a + 1;
console.log(`re-rendering and value of a is ${a}...`);
});Issue:
"re-rendering and value of a is 1..." every time.a is reinitialized to 0 during every render.Solution: Using useRef to Persist ValuesuseRef allows us to persist a value across renders without resetting it:
const a = useRef(0);
useEffect(() => {
a.current = a.current + 1;
console.log(`re-rendering and value of a is ${a.current}...`);
});Advantages of useRef:
a.current persists across renders.useState, changing useRef values does not trigger re-renders.Comparison of Approaches:
useState: Triggers re-renders upon value change.useRef: Retains the updated value across renders without causing re-renders.useRefScenario:
We have a counter button and need to change its background color without direct DOM manipulation.
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>Solution:
Use useRef to reference the DOM element and apply styles in useEffect.
const ref = useRef(); // Create a reference
useEffect(() => {
ref.current.style.backgroundColor = "red"; // Modify the DOM element
}, []); // Only runs on the first render
return (
<button ref={ref} onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
);Key Points:
useRef provides a reference(or access) to the DOM element, enabling style changes without manually querying the DOM (e.g., document.getElementById).useRef do not trigger re-renders.1. React Context API
createContext and useContext2. React Router
BrowserRouter, Routes, and RouteuseNavigate, useParams, and useLocation3. State Management Libraries
4. Performance Optimization
React.memo, useMemo, useCallback)React.lazy and Suspense5. Advanced React Patterns
6. Backend Integration
fetch or libraries like AxiosuseEffect for side effects7. TypeScript with React