0% found this document useful (0 votes)
8 views18 pages

REACT

A Single Page Application (SPA) loads a single HTML page and updates content dynamically using JavaScript, often with React. React components can be functional or class-based, with state management handled through hooks like useState and useEffect for side effects. Props are read-only inputs from parent to child components, while state is internal data that can change over time, and hooks like useCallback and useMemo help optimize performance by memoizing functions and values.

Uploaded by

sarthakkharka
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

REACT

A Single Page Application (SPA) loads a single HTML page and updates content dynamically using JavaScript, often with React. React components can be functional or class-based, with state management handled through hooks like useState and useEffect for side effects. Props are read-only inputs from parent to child components, while state is internal data that can change over time, and hooks like useCallback and useMemo help optimize performance by memoizing functions and values.

Uploaded by

sarthakkharka
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

wA Single Page Web Application (SPA) is a web application that loads one HTML page

initially and then dynamically updates the content without reloading the entire page. All
navigation and data updates happen through JavaScript, typically using APIs.

React is commonly used to build SPAs.

How a SPA Works

1.​ Browser loads a single [Link] file.​

2.​ JavaScript (React) is loaded.​

3.​ React renders UI components dynamically.​

4.​ When the user navigates or performs actions:​

○​ No full page reload​

○​ React updates only the required components​

○​ Data is fetched via APIs (REST/GraphQL)​

JSX is a syntax extension for JavaScript used in React that allows developers to write
HTML-like code inside JavaScript.

Interview-Ready Answer: Difference Between Functional and Class


Components (React)

Function Components vs Class


Components in React
1) Function Components
Function components are plain JavaScript functions that return JSX.​
They use Hooks to manage state and lifecycle.

function Counter() {

const [count, setCount] = [Link](0);


return <button onClick={() => setCount(count +
1)}>{count}</button>;

2) Class Components
Class components are ES6 classes that extend [Link].​
They manage state using [Link] and lifecycle methods.

Class components manage state using [Link] and setState(), and manage
lifecycle using methods like componentDidMount, componentDidUpdate, and
componentWillUnmount to control behavior during mounting, updating, and unmounting
phases.

class Counter extends [Link] {

constructor() {

super();

[Link] = { count: 0 };

render() {

return (

<button onClick={() => [Link]({ count:


[Link] + 1 })}>

{[Link]}

</button>

);

}
In React, a stateless component is a component that does not manage or store data or
manage its state and only renders UI based on the data it receives through props.

Thy simply receive data via props and renders by not maintaining any state

They are used when we dont need tohandle any complex logic

A stateful component, on the other hand, manages its own state using React state
(useState in functional components or [Link] in class components). It controls
behavior and data changes over time, such as user interactions, API responses, or form
inputs.

Props (short for properties) are read-only inputs passed from a parent
component to a child component in React. They are used to share data and
configuration between components and make components reusable and
dynamic.

They are read-only, meaning child components cannot modify them, and are used to
trigger actions in child components.
In React, props are read-only inputs passed from a parent component to a
child component, used to configure and reuse components.​
State, on the other hand, is internal data managed by a component itself
and can change over time in response to user actions or API calls.

Props represent what is passed into a component, while state represents


what is managed inside a component. Changes in either props or state cause
the component to re-render, but only the component that owns the state can
update it.

Answer:​
State is data managed inside a component that can change over time and trigger re-renders
when updated.

Why Hooks exist


Before Hooks, only class components could manage state and lifecycle. Hooks were
introduced to:

●​ Make components simpler and cleaner


●​ Reuse logic easily
●​ Avoid complex class syntax
●​ Improve readability and maintainability​

What is useState?
useState is a React Hook that allows functional components to store and update state.

Before hooks, only class components could have state. With useState, functional
components can manage state easily.

useEffect — When to Use & How It Works

What is useEffect?

useEffect is a React Hook used to handle side effects in functional components.

A side effect is anything that happens outside rendering, such as:


●​ API calls
●​ Updating document title​

When to Use useEffect


Use useEffect whenever you need to sync your component with something external.

Common Use Cases

1.​ Fetch data from an API​

2.​ Add/remove event listeners​

3.​ Start/stop timers​

4.​ Subscribe/unsubscribe to sockets​

5.​ Update document title​

6.​ Perform cleanup when component unmounts

Basic Syntax
useEffect(() => {

// side effect logic

return () => {

// cleanup logic (optional)

};

}, [dependencies]);

How useEffect Works


1.​ React renders the component.​

2.​ After the DOM is updated, React runs the useEffect callback.​

3.​ If dependencies change, React:​

○​ runs cleanup of previous effect​


○​ then runs the effect again.​

Dependency Array — The Key Concept


1) No dependency array

useEffect(() => {

[Link]("Runs after every render");

});

Runs after every render.

2) Empty dependency array []

useEffect(() => {

[Link]("Runs only once");

}, []);

Runs once when component mounts.

3) With dependencies

useEffect(() => {

[Link]("Runs when count changes");

}, [count]);

Runs only when count changes.

Real Example — API Call


useEffect(() => {

async function fetchData() {

const res = await fetch("/api/users");

const data = await [Link]();


setUsers(data);

fetchData();

}, []);

// useContext() = React Hook that allows you to share values

// between multiple levels of components

// without passing props through each level

useContext lets you share data between components without passing props
through every level.

Instead of:

A → B → C → D (props)

You use:

Context → any component

The 3 parts of Context API


1) Create Context
import { createContext } from "react";

export const UserContext = createContext();


Important:

●​ UserContext is not data​

●​ It is a container for data​

●​ Like a pipe that carries values​

2) Provide Context (Provider)


Your code (fixed):

import React, { useState, createContext } from "react";

import Cb from "./Cb";

export const UserContext = createContext();

function Ca() {

const [user, setUser] = useState("HELLO"); // ❌ removed "new"

return (

<div className="box">

<h1>This is Component A</h1>

<h2>{user}</h2>

<[Link] value={user}>

<Cb />

</[Link]>

</div>
);

export default Ca;

What happens here?

●​ [Link] wraps components​

●​ value={user} is the data being shared​

●​ Every component inside <Provider> can access user​

3) Consume Context (useContext)


import React, { useContext } from "react";

import { UserContext } from "./Ca";

function Cd() {

const user = useContext(UserContext);

return (

<div className="box">

<h1>This is Component D</h1>

<h2>{user}</h2>

</div>

);
}

export default Cd;

What this line does

const user = useContext(UserContext);

It:

1.​ Reads the value from the nearest Provider​

2.​ Subscribes to changes​

3.​ Re-renders when value changes​

Important rule (interview point)


Provider and Consumer must use the same context object.

This is correct in your code:

export const UserContext = createContext();

import { UserContext } from "./Ca";

Lifecycle of your example


1.​ Ca creates state → "HELLO"​

2.​ [Link] shares "HELLO"​

3.​ Cb renders​

4.​ Cd uses useContext(UserContext)​


5.​ Cd receives "HELLO" directly​
(no props, no drilling)

In React, whenever a component re-renders, all the values and calculations inside that
component are re-executed. If there is a heavy or expensive computation, this can impact
performance. To optimize this, we use the useMemo hook.

useMemo memoizes the result of a computation and reuses the cached value on subsequent
renders, unless its dependencies change. This prevents unnecessary recalculations and
improves performance.

The dependency array controls when the value should be recomputed:

●​ With an empty array, the computation runs only once.​

●​ With dependencies, it runs only when those dependencies change.​

●​ Without the array, it runs on every render.

What is useCallback?
useCallback is a React Hook used to memoize a function.​
It returns the same function reference between renders unless its
dependencies change.

Why do we need it?


In React, every time a component re-renders, new functions are
created.​
If these functions are passed to child components, React may think
the props changed and re-render the child unnecessarily.

useCallback prevents this by keeping the same function reference.

Syntax
const memoizedFn = useCallback(() => {

// logic

}, [dependencies]);

What it does (simple words)


It remembers your function and gives you the same function
again on the next render.

Interview explanation
useCallback is used to memoize callback functions so that
they are not recreated on every render. This helps prevent
unnecessary re-renders of child components, especially when
passing functions as props to components wrapped with
[Link].

Simple example
const handleClick = useCallback(() => {

[Link]("Clicked");

}, []);

●​ The function is created once.​

●​ On every re-render, React returns the same function.​


●​ Child components receiving this function do not re-render
unnecessarily.​

Dependency array behavior


1.​[] → function is created once.​

2.​[a, b] → new function is created only when a or b changes.​

3.​No array → new function every render (no benefit).​

One-line definition
useCallback memoizes functions to keep their reference
stable across renders and avoid unnecessary re-renders.

If you want, I can now give:

●​ A 30-second interview script​

●​ Or a real-world analogy​

●​ Or compare it again with useMemo in one clean table​

write eg also of callback

Here is a simple, clear example of useCallback with explanation.

Example: Prevent unnecessary child


re-render
Code

import { useState, useCallback } from "react";

const Child = [Link](({ onClick }) => {

[Link]("Child rendered");

return <button onClick={onClick}>Click me</button>;

});

function App() {

const [count, setCount] = useState(0);

const handleClick = useCallback(() => {

[Link]("Button clicked");

}, []); // memoized function

return (

<>

<button onClick={() => setCount(count +


1)}>Increase</button>

<Child onClick={handleClick} />

</>

);

export default App;


What happens (flow)

First render

●​ handleClick is created once by useCallback.​

●​ Child renders → console shows: “Child rendered”.​

Click Increase

●​ App re-renders because count changed.​

●​ useCallback returns the same function reference.​

●​ [Link] compares props:​

○​ old onClick === new onClick → true​

●​ Child does not re-render.​

Click Click me

●​ Browser fires click event.​

●​ React calls handleClick.​

●​ Console shows: “Button clicked”.​

Why this works


●​ useCallback keeps the same function in memory.​
●​ [Link] skips rendering when props are the same by
reference.​

●​ Result: better performance, no unnecessary re-renders.​

One-line interview answer


useCallback memoizes a function so its reference stays the
same across renders, which helps prevent unnecessary
re-renders when passing callbacks to memoized child
components.

If you want, I can also show:

●​ The same example without useCallback for comparison.​

●​ Or a real-world analogy to remember it easily.

What happens

●​ increment is memoized.
●​ Button receives the same function reference.
●​ Button does not re-render when parent state changes unrelated to it.

useCallback vs useMemo

Hook What Returns


it
memo
izes
useCallb A The same
ack(fn, functio function
deps) n reference

useMemo( A The computed


fn, value result
deps)

Equivalent conceptually:

useCallback(fn, deps) === useMemo(() => fn, deps)

When you SHOULD use useCallback


Use it when:

1.​ Passing a function to a memoized child component ([Link])


2.​ Using a function inside useEffect dependency array
3.​ Preventing re-creation of handlers in performance-sensitive components

When you should NOT use it


Do not use useCallback everywhere.

Avoid if:

●​ The function is not passed as a prop


●​ The component is small and not performance-critical
●​ You are not facing re-render issues

Overusing it adds complexity without benefit.

Common Mistake
Incorrect dependencies:

const fn = useCallback(() => {

[Link](value);

}, []); // ❌ value is missing


Correct:

const fn = useCallback(() => {

[Link](value);

}, [value]);

Always include everything used inside the function in the dependency array.

One-line interview answer


useCallback memoizes a function so React keeps the same function
reference between renders, preventing unnecessary re-renders and effect
re-executions when dependencies haven’t changed.

If you want, I can now explain:

●​ useCallback with useReducer


●​ useCallback vs useRef
●​ Or a real project-level optimization example.

We use the useRef hook to store values that are not directly related to
rendering.​
It provides a current property that we can change, and updating this value
does not trigger a re-render.

useRef is commonly used to interact with the DOM, for example with input
elements.​
It allows us to access browser-related properties and methods, such as
focusing an input, reading its value, or controlling elements directly.

You might also like