What are the benefits of React?

Benefits of ReactJS (For Interviews)

  1. Component-Based Architecture
  2. Encourages reusability and separation of concerns.
  3. Makes code more modular, readable, and maintainable.
  4. Virtual DOM for Better Performance
  5. React uses a virtual DOM to minimize direct DOM manipulation.
  6. Improves app speed by updating only the changed components.
  7. Unidirectional Data Flow
  8. Data flows in one direction, making it easier to debug and predict how the app behaves.
  9. Strong Ecosystem and Community Support
  10. Large community means more libraries, tools, and faster problem solving.
  11. Well-supported by Facebook and widely adopted in the industry.
  12. JSX – JavaScript + HTML
  13. JSX simplifies writing UI logic and makes the code easier to understand.
  14. Rich Developer Tools
  15. React DevTools extension helps in debugging and inspecting component hierarchies.
  16. Easy to Learn and Use
  17. Developers with JavaScript knowledge can quickly learn and use React effectively.
  18. SEO-Friendly with SSR
  19. React can be rendered on the server side (e.g., using Next.js), making it better for SEO.
  20. Strong Integration Capabilities
  21. Easily integrates with other libraries or frameworks like Redux, React Router, Axios, etc.
  22. Cross-Platform Development
  23. Can be used to build web apps (React) and mobile apps (React Native) with shared logic.

You can end by saying:

"Overall, React’s simplicity, flexibility, and performance make it a powerful tool for building modern, scalable user interfaces."

Difference Between State and Props in React

✅ Quick Analogy:

  1. Props = function parameters → passed in, read-only.
  2. State = variables inside a function → can change based on logic/events.

🧠 Sample Interview Answer:

“Props are used to pass data from parent to child components and are immutable. State, on the other hand, is local to the component and used to track data that can change over time, like form input or toggles. Props make components reusable, while state helps manage interactivity.”


import React, { useState } from 'react';
// Parent Component
function App() {
return (
<div>
<h1>React Props vs State</h1>
<Counter title="My Counter" />
</div>
);
}
// Child Component using props and state
function Counter({ title }) {
const [count, setCount] = useState(0); // state
const handleIncrement = () => {
setCount(prev => prev + 1); // updating state
};
return (
<div>
<h2>{title}</h2> {/* Using props */}
<p>Count: {count}</p> {/* Using state */}
<button onClick={handleIncrement}>Increment</button>
</div>
);

}
export default App;










What is the component lifecycle in functional components?

Summary:

  1. Mount → empty dependency array ([])
  2. Update → dependency array with specific state/props ([count])
  3. Unmount → return a function inside useEffect

You can say in your interview:

"In functional components, we use the useEffect hook to handle lifecycle events. It can mimic componentDidMount, componentDidUpdate, and componentWillUnmount depending on how the dependencies are managed."

What are Hooks in React?

Hooks are special functions introduced in React 16.8 that let you use state and other React features (like lifecycle methods) in functional components, without writing a class.

Some common hooks:

  1. useState – for managing local state
  2. useEffect – for side effects (e.g., API calls, timers)
  3. useRef – for referencing DOM elements or persisting values without re-rendering


When is the useRef Hook Used?

useRef is used when you want to:

  1. Access or interact with DOM elements directly (like focusing an input field).
  2. Store mutable values that persist across renders but don’t trigger re-renders when changed (like a timeout ID or previous value).
import React, { useRef } from 'react';

function InputFocus() {
const inputRef = useRef();

const handleFocus = () => {
inputRef.current.focus(); // Access DOM node directly
};

return (
<>
<input ref={inputRef} type="text" />
<button onClick={handleFocus}>Focus Input</button>
</>
);
}

Interview Tip:

"useRef is ideal when I need to persist values across renders or directly access DOM elements without causing a re-render. It’s often used for focus control, timers, or tracking previous values."


How do you avoid re-rendering of a component?

"I use React.memo to memoize components, and useMemo/useCallback to prevent unnecessary recalculations or function recreations. I also ensure object references don’t change unless needed and avoid unnecessary state updates to reduce re-renders."


How to Avoid Re-Rendering in React

  1. React.memo() – Wrap functional components to memoize them so they only re-render when props change.
const MyComponent = React.memo((props) => {
// only re-renders if props change
return <div>{props.value}</div>;
});
  1. useMemo() – Memoizes expensive computations to avoid recalculating on every render.
const expensiveValue = useMemo(() => computeValue(a, b), [a, b]);
  1. useCallback() – Prevents function re-creation on every render, useful when passing callbacks to child components.

const handleClick = useCallback(() => {

doSomething();
}, [dependency]);
  1. Avoid Changing References – Don’t recreate objects/arrays/functions inside render unless necessary.
  2. Use key properly in lists – Helps React identify which items changed and avoid unnecessary DOM updates.
  3. Split Large Components – Break down large components into smaller ones to isolate re-renders.


How to Optimize a React Application

  1. Use React.memo
  2. Prevents unnecessary re-renders of functional components by memoizing them unless props change.
  3. Use useMemo and useCallback
  4. useMemo → Memoizes expensive calculations.
  5. useCallback → Memoizes function instances to avoid re-creating them on every render.
  6. Code Splitting with React.lazy & Suspense
  7. Load components only when needed (lazy loading) to reduce initial bundle size.
  8. Virtualize Long Lists
  9. Use libraries like react-window or react-virtualized to render only visible items in large lists.
  10. Optimize Images and Assets
  11. Compress images, use lazy loading (loading="lazy"), and serve scaled versions based on screen size.
  12. Avoid Anonymous Functions in JSX
  13. They create new instances on every render – move them outside the render or use useCallback.
  14. Debounce or Throttle Expensive Events
  15. For input handling, scroll, or resize events, use debounce/throttle to reduce excessive re-renders.
  16. Remove Unused State or Props
  17. Keep your component clean and minimal – less state means fewer updates and re-renders.
  18. Keep Component Tree Shallow
  19. Avoid deeply nested components – it makes debugging and performance optimization harder.

🧠 Interview Summary Line:

"To optimize a React app, I use memoization (React.memo, useMemo, useCallback), lazy loading, virtualized lists, and avoid unnecessary renders by minimizing state and avoiding anonymous functions inside JSX."


What are Higher-Order Components (HOCs)?

A Higher-Order Component is a function that takes a component and returns a new one with additional behavior. I use HOCs to reuse logic like logging, authentication, or conditional rendering across multiple components.


What is the Virtual DOM in React?

The Virtual DOM (V-DOM) is a lightweight JavaScript representation of the real DOM. React uses it to track changes in the UI efficiently.

Instead of directly manipulating the real DOM (which is slow), React first updates the virtual DOM, calculates the difference (diffing), and then updates only the changed parts in the real DOM.

🚀 How Does It Improve Performance?

  1. Minimizes Direct DOM Manipulations: Real DOM updates are expensive; virtual DOM reduces the number of these operations.
  2. Efficient Diffing: React compares the old and new virtual DOM and finds the minimal set of changes.
  3. Batch Updates: React batches updates to the real DOM, reducing reflows and repaints.

🧠 Interview Summary:

"The Virtual DOM is a copy of the real DOM stored in memory. React uses it to detect changes efficiently and update only what's necessary in the real DOM, which significantly improves app performance."


Steps to Handle a 404 Page in React Router (v6+):

  1. Define a fallback route with * as the path.
  2. Place it at the end of your route list.
  3. Render your custom 404 component there.

🧩 Example:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound'; // 404 component
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
{/* 404 Route */}
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
);
}

🧠 Interview Summary:

"In React Router, I handle 404 pages by using a route with path='*', which catches all undefined routes and renders a custom NotFound component."


Difference Between Stateless and Stateful Components in React


"A stateless component only relies on props and doesn't manage any internal data, while a stateful component holds and manages its own state, often using hooks like useState."


Stateless Component:

const Greeting = ({ name }) => <h2>Hello, {name}!</h2>;

Stateful Component:

import { useState } from 'react';

const Counter = () => {
const [count, setCount] = useState(0);
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
};

How to Handle Side Effects in React


In functional components, I use the useEffect hook to handle side effects like API calls, subscriptions, and manual DOM updates. I also use its cleanup function to prevent memory leaks

useEffect(() => {
// Side effect logic (e.g., API call)

return () => {
// Cleanup function (e.g., clear timer, unsubscribe)
};
}, [dependencies]);


What is Redux, and how do you handle API calls in Redux?

What is Redux?

Redux is a predictable state management library for JavaScript applications, often used with React.

  1. It stores application state in a centralized store.
  2. Components access state via useSelector and dispatch actions via useDispatch.
  3. The state updates through reducers in response to dispatched actions.

⚙️ Core Concepts of Redux:

  1. Store: Holds the entire state of the application.
  2. Actions: Plain objects that describe events ({ type: 'INCREMENT' }).
  3. Reducers: Pure functions that update the state based on actions.
  4. Dispatch: Sends actions to the reducer.

🌐 How to Handle API Calls in Redux

To handle asynchronous operations like API calls, you typically use middleware, such as:

  1. Redux Thunk (most common)
  2. Redux Toolkit (with built-in thunk support)
  3. Redux Saga (for more complex workflows)

🔧 Example with Redux Thunk:

// Action Creator (Thunk)
export const fetchUsers = () => {
return async (dispatch) => {
dispatch({ type: "FETCH_USERS_REQUEST" });
try {
const response = await fetch("https://api.example.com/users");
const data = await response.json();
dispatch({ type: "FETCH_USERS_SUCCESS", payload: data });
} catch (error) {
dispatch({ type: "FETCH_USERS_FAILURE", error: error.message });
}
};
};
  1. Dispatch in Component:
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchUsers());
}, []);

🧠 Interview Summary Line:

"Redux is a state management library that maintains a centralized store. I handle API calls using middleware like Redux Thunk, where I dispatch async actions to fetch data and update the state accordingly."


What is a closure, and how is it used?

What is a Closure in JavaScript?

A closure is a function that remembers the variables from its lexical scope, even when the function is executed outside that scope.

🔍 In Simple Terms:

If an inner function accesses variables from an outer function, even after the outer function has finished executing, it's called a closure.

📦 Why Is It Useful?

Closures allow:

  1. Data encapsulation (private variables)
  2. Persistent state across function calls
  3. Callback functions with remembered context

🔧 Example:

function outer() {
let count = 0;

return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2

Even though outer() has finished running, the inner() function still remembers count — this is a closure.

🧠 Interview Summary:

"A closure is when a function remembers the variables in its lexical scope even after the outer function has finished. It's used for things like data privacy, stateful functions, and maintaining access to variables across executions.


What is the difference between map and forEach methods?


map() returns a new array with transformed elements and is used when you need to store the result, while forEach() just iterates and is used for side effects like logging or DOM updates.


const numbers = [1, 2, 3];
// map – returns a new array
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

// forEach – performs an action, no return
numbers.forEach(num => console.log(num * 2));


What is hoisting in JavaScript?


Hoisting is the behavior where variable and function declarations are moved to the top of their scope before execution. Unlike var, let and const are hoisted but not initialized, leading to a temporal dead zone

📌 Key Points:

  1. Variable and function declarations are hoisted.
  2. Only the declarations are hoisted, not initializations.
  3. var is hoisted differently than let and const.

🔧 Example:

console.log(x); // undefined (not error!)
var x = 5;

Internally, JavaScript interprets it like:

var x;
console.log(x); // undefined
x = 5;

But with let or const:

console.log(y); // ❌ ReferenceError
let y = 10;



What are semantic tags in HTML?

Semantic tags are HTML elements that clearly describe their meaning and purpose both to the browser and developers. They make the HTML structure more readable, accessible, and SEO-friendly.


<main>
<article>
<header>
<h1>Blog Title</h1>
</header>
<p>This is the blog content.</p>
<footer>Author: Shamim</footer>
</article>
</main>

Semantic tags like <header>, <nav>, <section>, and <footer> make HTML more meaningful, improve accessibility for screen readers, and help search engines better understand the page structure


What is an arrow function in JavaScript?

An arrow function is a shorter syntax for writing function expressions in JavaScript. It was introduced in ES6 and has a special behavior with the this keyword.

📌 Syntax:

// Regular function
function add(a, b) {
return a + b;
}

// Arrow function
const add = (a, b) => a + b;


🧠 Interview Summary Line:

"Arrow functions provide a concise syntax and do not have their own this context. They’re ideal for short callbacks and functions where lexical this binding is preferred."



What is the event loop in JavaScript?

What Is the Event Loop in JavaScript?

The event loop is a mechanism in JavaScript that handles the execution of code, collects events, and processes tasks from the callback queue after the call stack is empty.

JavaScript is single-threaded, so it uses the event loop to manage non-blocking asynchronous tasks like setTimeout, API calls, and promises.

he event loop allows JavaScript to handle asynchronous operations by pushing callbacks from the queue to the call stack once it’s empty, enabling non-blocking execution in a single-threaded environment.


What is the difference between a development dependency and a regular

dependency?

Regular dependencies are needed to run the application in production, while development dependencies are only used during development for tools like testing, bundling, or linting


How They’re Defined in package.json:

"dependencies": {
"react": "^18.2.0"
},
"devDependencies": {
"eslint": "^8.56.0"
}

Examples:

  1. Regular Dependencies (dependencies):
  2. React, Axios, Express — used in the actual application logic.
  3. Development Dependencies (devDependencies):
  4. Webpack, ESLint, Babel, Jest — used for building, testing, or formatting code during development.


What is debouncing, and how is it implemented?

What Is Debouncing?

Debouncing is a technique used to limit how often a function gets called. It ensures a function is only executed after a specified delay has passed since the last time it was invoked.

It’s commonly used for:

  1. Search input
  2. Resize or scroll events
  3. Button click prevention

🔧 How It Works:

  1. When the function is triggered multiple times (like while typing), it waits for a pause.
  2. If another trigger happens during the wait, the timer resets.

🛠️ Basic Debounce Implementation:

function debounce(func, delay) {
let timeoutId;

return function (...args) {
clearTimeout(timeoutId); // Clear any previous timer
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}

📌 Usage Example:

function handleSearch(value) {
console.log("Searching for:", value);
}
const debouncedSearch = debounce(handleSearch, 300);
// Suppose this is called on every keystroke:
inputElement.addEventListener("input", (e) => {
debouncedSearch(e.target.value);
});

🧠 Interview Summary Line:

"Debouncing is a performance optimization technique that ensures a function is executed only after a certain delay of inactivity. It’s useful in scenarios like search input or resize events to prevent excessive function calls."


Write code to reverse your name spelling

const name = "Md Shamim Akhter";
const reversedName = name.split("").reverse().join("");

console.log("Reversed Name:", reversedName);


Create a table component from an array of objects in React

Table Component (UserTable.jsx):

import React from 'react';
const UserTable = ({ data }) => {
return (
<div className="p-4">
<table className="w-full border-collapse border border-gray-300">
<thead>
<tr className="bg-gray-200">
<th className="border border-gray-300 px-4 py-2">ID</th>
<th className="border border-gray-300 px-4 py-2">Name</th>
<th className="border border-gray-300 px-4 py-2">Email</th>
</tr>
</thead>
<tbody>
{data.map((user) => (
<tr key={user.id}>
<td className="border border-gray-300 px-4 py-2">{user.id}</td>
<td className="border border-gray-300 px-4 py-2">{user.name}</td>
<td className="border border-gray-300 px-4 py-2">{user.email}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default UserTable;









Usage in App:

import React from 'react';
import UserTable from './UserTable';
const App = () => {
const users = [
{ id: 1, name: "Shamim", email: "shamim@example.com" },
{ id: 2, name: "John", email: "john@example.com" },
{ id: 3, name: "Alice", email: "alice@example.com" }
];
return (
<div className="min-h-screen flex items-center justify-center bg-white">
<UserTable data={users} />
</div>
);
};
export default App;


Handle an API request from a component using fetch or Axios




import React, { useEffect, useState } from 'react';
const UserListFetch = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) throw new Error("Network response was not ok");
const data = await response.json();
setUsers(data);
} catch (error) {
console.error("Fetch error:", error);
} finally {
setLoading(false);
}
};

fetchUsers();
}, []);
return (
<div>
<h2>Users (Fetch)</h2>
{loading ? <p>Loading...</p> : (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
)}
</div>
);
};
export default UserListFetch;

















import React, { useEffect, useState } from 'react';
import axios from 'axios';
const UserListAxios = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const getUsers = async () => {
try {
const res = await axios.get("https://jsonplaceholder.typicode.com/users");
setUsers(res.data);
} catch (error) {
console.error("Axios error:", error);
} finally {
setLoading(false);
}
};
getUsers();
}, []);
return (
<div>
<h2>Users (Axios)</h2>
{loading ? <p>Loading...</p> : (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
)}
</div>
);
};
export default UserListAxios;














How do you create a responsive web page?

I ensure responsiveness using the viewport meta tag, relative units, Flexbox/Grid layout, media queries, and by optimizing images. I may also use frameworks like Tailwind or Bootstrap to speed up developmen


Key Techniques to Create a Responsive Web Page:

  1. Use a Responsive Meta Tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
This ensures the layout adjusts to the device's screen width.
  1. Use Relative Units (%, em, rem, vw, vh) Instead of Fixed px:
.container {
width: 80%; /* Instead of fixed pixels */
font-size: 1.2rem;
}
  1. Use Flexbox or Grid Layout:
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
  1. Media Queries for Breakpoints:
@media (max-width: 768px) {
.container {
flex-direction: column;
}
}
  1. Responsive Images:
<img src="image.jpg" style="width: 100%; height: auto;" />
  1. Frameworks (Optional but Helpful):
  2. Tailwind CSS – utility-first, responsive classes like md:flex, sm:hidden.
  3. Bootstrap – grid system with responsive breakpoints.


What is the difference between CSS and SASS?


CSS (Cascading Style Sheets)

  1. Standard styling language for web pages.
  2. Styles are written directly without any advanced features.
  3. No variables, nesting, or functions (vanilla CSS).
.container {
color: blue;
padding: 20px;
}

✅ SASS (Syntactically Awesome Style Sheets)

  1. A CSS preprocessor that extends CSS with powerful features.
  2. Requires a compiler (e.g., sass CLI or tools like Webpack).
  3. Supports:
  4. Variables
  5. Nesting
  6. Mixins
  7. Functions
  8. Inheritance
$primary-color: blue;

.container {
color: $primary-color;
padding: 20px;

.child {
font-weight: bold;
}
}


How do you center a div with text on the page?

1. Using Flexbox (Modern and Recommended)

<div class="center-box">
This is centered text.
</div>
body, html {
height: 100%;
margin: 0;
}
.center-box {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
height: 100vh;
font-size: 20px;
background: #f0f0f0;
}

✅ 2. Using CSS Grid

.center-box {
display: grid;
place-items: center;
height: 100vh;
}

✅ 3. Using Position + Transform

.center-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

✅ Summary (for Interviews):

“I usually center content using Flexbox or Grid. Flexbox with justify-content and align-items is very readable and responsive-friendly.”


What is event propagation?

Event propagation in JavaScript refers to the order in which events are handled in the DOM tree. It happens in three phases:

✅ Three Phases of Event Propagation:

  1. Capturing Phase (Capture/Bubbling down):
  2. The event starts from the window and travels down the DOM tree to the target element.
  3. Target Phase:
  4. The event reaches the target element (the one that was clicked or interacted with).
  5. Bubbling Phase:
  6. The event then bubbles up from the target back to the root (window).

✅ Example:

<div id="parent">
<button id="child">Click me</button>
</div>

document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});

document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
When the button is clicked, the logs will be:


Child clicked
Parent clicked

— because bubbling is the default.

✅ To Use Capturing:

element.addEventListener("click", handler, true); // third param true = capture

✅ Prevent Propagation:

  1. To stop bubbling or capturing:
event.stopPropagation();

📝 Summary (for interviews):

“Event propagation determines how events flow in the DOM: first capturing from root to target, then bubbling from target to root. We can control or stop propagation using stopPropagation().”


Apply an animation using CSS.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS Animation Example</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="box"></div>
</body>
</html>


/* Styling for the box */
.box {
width: 150px;
height: 150px;
background-color: #3498db;
margin: 100px auto;
border-radius: 10px;
/* Apply animation */
animation: slideFadeIn 2s ease-in-out forwards;
}
/* Keyframes for animation */
@keyframes slideFadeIn {
0% {
opacity: 0;
transform: translateY(-50px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}




Summary (for interviews):

“In CSS, animations are defined using @keyframes, and applied via the animation property. You can animate properties like opacity, transform, color, etc., to enhance user experience.”


How do you maintain code quality?

I maintain code quality through a combination of peer code reviews, consistent styling with linting tools, automated unit tests, modular coding practices, proper version control, and CI/CD pipelines. I also prioritize performance, write good documentation, and refactor the code as necessary to keep it maintainable


Explain your strengths and weaknesses

My strengths include strong problem-solving skills, attention to detail, adaptability, and being a collaborative team player. On the other hand, I’ve recognized areas for improvement, such as managing perfectionism, delegating tasks effectively, overcoming public speaking anxiety, and avoiding overcommitment. I’m continuously working on improving these aspects to become a more effective professional.


What are your future plans?

"I aim to grow technically by mastering advanced React, Node.js, and state management. My long-term goal is to transition into a Senior Developer role, where I can contribute to team development and take on leadership responsibilities. Ultimately, I want to keep evolving as both a developer and a mentor."


What is the difference between shallow and mount in testing?


How does the useEffect hook work in functional components?


The useEffect hook in React allows you to handle side effects in functional components, such as data fetching, subscribing to external APIs, or manipulating the DOM. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

Key Points:

  1. Syntax:
useEffect(() => {
// Side effect code here (e.g., API calls, DOM updates)
}, [dependencies]);
  1. How it works:
  2. Without dependencies: The effect runs after every render.
  3. With an empty array ([]): The effect runs once after the first render (component mount).
  4. With specific dependencies: The effect runs when one of the dependencies in the array changes.
  5. Example:
import React, { useState, useEffect } from 'react';
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Effect ran: count changed');
}, [count]); // Runs when `count` changes
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
  1. Cleaning up effects: If the effect involves subscriptions, timers, or any other side effects that need cleanup, you can return a cleanup function inside the useEffect. This function will run either before the effect runs again or when the component unmounts.
  2. Example:
useEffect(() => {
const timer = setTimeout(() => {
console.log('Timer triggered');
}, 1000);

// Cleanup function
return () => clearTimeout(timer); // Clears timer when component unmounts or before effect runs again
}, []);

Why it's useful:

  1. It provides a clean and simple way to handle side effects in functional components.
  2. It helps in reducing the need for class components, making the code more readable and concise.

When to use:

  1. Fetching data: Trigger API calls after the component mounts.
  2. DOM updates: Direct DOM manipulations like updating the scroll position.
  3. Timers/Intervals: Setting timeouts or intervals.
  4. Subscriptions: For WebSockets, event listeners, or other external sources.


How do you implement routing in a React application?

To implement routing in a React application, we use the react-router-dom library. This allows us to manage navigation between different views or pages without reloading the entire page, which is typical of a Single Page Application (SPA).

Steps to Implement Routing:

  1. Install react-router-dom:
  2. Install the library using npm or yarn:
npm install react-router-dom
  1. Set up Router in your App.js:
  2. You need to wrap your entire application in a BrowserRouter to enable routing.
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
const Home = () => <h2>Home Page</h2>;
const About = () => <h2>About Page</h2>;
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
</Router>
);
}

export default App;
  1. Routing Components:
  2. BrowserRouter wraps the app to manage history and the URL.
  3. Route specifies the component that should render for a specific path.
  4. Switch ensures that only the first matching route is rendered.
  5. Link is used to navigate between routes without reloading the page.
  6. Dynamic Routing:
  7. You can also define dynamic routes using route parameters:
const UserProfile = ({ match }) => {
const userId = match.params.userId;
return <h2>User Profile: {userId}</h2>;
};
<Route path="/user/:userId" component={UserProfile} />
  1. Redirects & Conditional Routing:
  2. You can use Redirect for redirecting users programmatically or conditionally render routes based on authentication."