■■ React.
js
Complete Revision Guide & Cheat Sheet
Placement Prep · Technical Rounds · Last-Hour Revision
JS Basics → ES6 → DOM → Async → React Core → Hooks → Router → Redux → Auth
■ Table of Contents
1. JavaScript Foundations — Variables · Functions · Arrays · Objects · ES6
2. DOM & Async JavaScript — DOM · Promises · Async/Await · Fetch API
3. React Core — Intro · JSX · Components · Props · State · Events
4. React Hooks — useState · useEffect · useRef · useMemo · useCallback · useContext · useReducer · Custom
5. Rendering & Forms — Conditional · List Rendering · Form Handling · Lifecycle
6. API & Routing — API Integration · Axios · React Router · CRUD
7. State Management — Context API · useContext · Redux Toolkit
8. Auth & Advanced — JWT · Protected Routes · Performance · Error Handling · Env Vars
✦. Super Cheat Sheet — One-page quick reference — all the essentials
[Link] Revision Guide · Page 2
1 JavaScript Foundations
● Variables & Data Types
var — function scoped, hoisted (avoid). let — block scoped, reassignable. const — block scoped, cannot reassign (object props can
change).
let name = 'React'; const PI = 3.14; var old = true;
// Types: string, number, boolean, null, undefined, symbol, BigInt
typeof null // 'object' (JS quirk!) typeof undefined // 'undefined'
// Falsy: false, 0, '', null, undefined, NaN
● Functions
3 ways to define: Function Declaration (hoisted), Function Expression, Arrow Function (no own this).
function add(a,b){ return a+b; } // declaration — hoisted
const mul = function(a,b){ return a*b; } // expression
const sub = (a,b) => a-b; // arrow — implicit return
const greet = name => `Hello ${name}`; // single param, template literal
// Default params
const pow = (base, exp=2) => base**exp;
// Rest params
const sum = (...nums) => [Link]((a,c)=>a+c,0);
● Arrays
Key methods for interviews — map, filter, reduce are most asked.
[Link](x => x*2) // new array [Link](x=>[Link](x))
[Link](x=>x>2) // subset [Link](3) // bool
[Link]((a,c)=>a+c,0) // single val [Link](depth) // flatten
[Link](x=>x>3) // first match [Link](1,3) // no mutation
[Link](x=>x>3) // index [Link](1,1,'new') // mutates
[Link](x=>x>3) // bool [...arr1,...arr2] // spread
● Objects
const user = { name:'Alice', age:25 };
// Destructuring
const { name, age=0 } = user;
// Spread / Rest
const updated = { ...user, age:26 };
// Optional chaining & Nullish coalescing
user?.address?.city ?? 'Unknown';
// Object methods
[Link](obj) [Link](obj) [Link](obj)
● ES6+ Concepts
Destructuring const [a,b]=[1,2]; const {x}=obj;
Spread / Rest fn(...args) | const n={...obj, key:val}
Template Literals `Hello ${name}, ${1+1}`
Modules export default App; import App from './App'
Classes class Animal { constructor(){} speak(){} }
Promises new Promise((res,rej)=>{ res(data) })
Symbol unique & immutable primitive — Symbol('id')
for...of for(const item of arr) — iterates values
[Link] Revision Guide · Page 3
2 DOM & Async JavaScript
● DOM Manipulation
Document Object Model — tree structure of HTML. JS can read/update it.
[Link]('id') // single element
[Link]('.class') // CSS selector
[Link]('div') // NodeList
[Link] = 'Hello'; [Link] = '<b>Hi</b>';
[Link] = 'red'; [Link]('active');
[Link]('click', handler); // attach event
[Link]('div') [Link](child)
● Promises
Promise — object representing eventual completion/failure of async op. States: pending → fulfilled / rejected.
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('done'), 1000);
});
[Link](val => [Link](val)) // 'done'
.catch(err => [Link](err))
.finally(() => [Link]('always runs'));
// Promise combinators
[Link]([p1,p2]) // wait for ALL — fails fast
[Link]([p1,p2]) // first to settle wins
[Link]([]) // all results regardless
● Async / Await
async makes a function return a Promise. await pauses execution until Promise resolves. Always wrap in try/catch for errors.
async function fetchUser(id) {
try {
const res = await fetch(`/api/user/${id}`);
if (![Link]) throw new Error('Network error');
const data = await [Link]();
return data;
} catch(err) { [Link](err); }
}
● Fetch API
Built-in browser API for HTTP requests. Returns a Promise.
// GET
fetch('/api/data').then(r=>[Link]()).then([Link]);
// POST
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: [Link]({ name: 'Alice' })
}).then(r=>[Link]());
[Link] Revision Guide · Page 4
3 React Core
● React Introduction
React is a JS library for building UIs using a component-based architecture. It uses a Virtual DOM — a lightweight copy of the real
DOM. On state change, React diffs the VDOM and updates only changed parts (reconciliation). Unidirectional data flow: data flows
parent → child.
● JSX
JSX = JavaScript XML. Syntactic sugar — compiles to [Link](). Must return a single root. Use fragments <> to avoid
extra DOM nodes.
// JSX rules
const el = <h1 className='title'>Hello</h1>; // class → className
const wrapped = <>{el}<p>World</p></>; // fragment
// Expressions in JSX
const name = 'Alice';
return <p>Hello, {[Link]()}!</p>; // {} for JS
// Compiles to:
[Link]('p', null, 'Hello, ', [Link]())
● Components
Everything in React is a component. Two types: Class Components (legacy) and Functional Components (modern, use hooks).
Component names must start with capital letter.
// Functional Component (preferred)
function Welcome({ name }) {
return <h1>Hello, {name}!</h1>;
}
// Class Component (legacy — know for interviews)
class Welcome extends [Link] {
render() { return <h1>Hello, {[Link]}</h1>; }
}
● Props
Props (properties) — read-only data passed from parent to child. Cannot be modified by the child. Like function arguments.
function Card({ title, count=0, children }) { // destructure + default
return <div><h2>{title}</h2><p>{count}</p>{children}</div>;
}
// Usage
<Card title='Users' count={42}><span>extra</span></Card>
// Spread props
const config = { title:'T', count:5 };
<Card {...config} />
● State
State — mutable data local to a component. Changing state triggers a re-render. Never mutate state directly — always use the
setter.
const [count, setCount] = useState(0);
// Updater function form (safe for async)
setCount(prev => prev + 1);
// Object state — spread to keep other keys
const [user, setUser] = useState({ name:'', age:0 });
setUser(prev => ({ ...prev, name: 'Alice' }));
Props vs State
Props State
Ownership Parent owns Component owns
Mutability Read-only Mutable via setter
Change Parent re-renders Component re-renders
● Event Handling
[Link] Revision Guide · Page 5
Events use camelCase. Pass a function reference, not a call. Synthetic events wrap native events — same API cross-browser.
// Basic event
<button onClick={() => setCount(c => c+1)}>+</button>
// With event object
function handleChange(e) { setValue([Link]); }
<input onChange={handleChange} value={value} />
// Prevent default
<form onSubmit={e => { [Link](); handleSubmit(); }}>
[Link] Revision Guide · Page 6
4 React Hooks
■ useState
Manages local component state.
const [val, setVal] = useState(initial);
setVal(newVal); // or setVal(prev => newVal)
■ useEffect
Side effects: data fetch, subscriptions, DOM updates. Runs after render. Deps array controls when it re-runs.
useEffect(() => {
fetchData(); // runs on every dep change
return () => cleanup();// cleanup on unmount
}, [dep1, dep2]); // [] = run once on mount
■ useRef
Mutable ref — persists across renders WITHOUT causing re-render. Also for DOM access.
const inputRef = useRef(null);
[Link](); // DOM access
const countRef = useRef(0); // mutable value
■ useMemo
Memoizes expensive computed value. Recalculates only when deps change.
const sorted = useMemo(()=>[Link]((a,b)=>a-b), [arr]);
// Use for: heavy computations, derived data
■ useCallback
Memoizes a function. Prevents child re-renders when passing callbacks.
const handleClick = useCallback(() => {
doSomething(id);
}, [id]); // new fn only when id changes
■ useContext
Consume Context without Consumer wrapper.
const theme = useContext(ThemeContext);
// Must be inside matching Provider
■ useReducer
useState alternative for complex state logic. Like Redux but local.
const [state, dispatch] = useReducer(reducer, initial);
dispatch({ type: 'INCREMENT', payload: 1 });
function reducer(state, action) {
switch([Link]) {
case 'INCREMENT': return { count: [Link]+[Link] };
default: return state;
}
}
■ Custom Hooks
Extract reusable stateful logic into a function starting with use. Can call other hooks inside. Returns anything useful.
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url).then(r=>[Link]()).then(d=>{setData(d);setLoading(false)});
}, [url]);
return { data, loading };
}
// Usage
const { data, loading } = useFetch('/api/users');
Rules of Hooks: 1) Only call at top level (not inside loops/if). 2) Only call from React functions or custom hooks.
[Link] Revision Guide · Page 7
5 Rendering, Forms & Lifecycle
● Conditional Rendering
Show/hide elements based on state or props.
// Ternary (most common)
{isLoggedIn ? <Dashboard /> : <Login />}
// && short-circuit (render or nothing)
{count > 0 && <span>{count} items</span>}
// if-else in function
if (loading) return <Spinner />;
if (error) return <Error msg={error} />;
return <DataView data={data} />;
● List Rendering
key prop is mandatory — helps React identify changed items. Use stable unique IDs, not array index (index = buggy with re-order).
const users = [{id:1,name:'Alice'},{id:2,name:'Bob'}];
return (
<ul>
{[Link](user => (
<li key={[Link]}>{[Link]}</li> // key must be unique
))}
</ul>
);
● Forms Handling
Controlled component — React state drives input value. Input value tied to state, onChange updates state.
function LoginForm() {
const [form, setForm] = useState({ email:'', pass:'' });
const handleChange = e => setForm({...form,[[Link]]:[Link]});
const handleSubmit = e => { [Link](); [Link](form); };
return (
<form onSubmit={handleSubmit}>
<input name='email' value={[Link]} onChange={handleChange}/>
<input name='pass' type='password' value={[Link]} onChange={handleChange}/>
<button type='submit'>Login</button>
</form>
);
}
● React Lifecycle (Functional)
No lifecycle methods in functional components — use useEffect.
// componentDidMount equivalent
useEffect(() => { fetchData(); }, []);
// componentDidUpdate equivalent
useEffect(() => { [Link] = count; }, [count]);
// componentWillUnmount equivalent
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id); // cleanup
}, []);
Class lifecycle (know for interviews): constructor → render → componentDidMount → componentDidUpdate → componentWillUnmount
[Link] Revision Guide · Page 8
6 API Integration & Routing
● API Integration Pattern
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('/api/users')
.then(r => { if(![Link]) throw new Error('Failed'); return [Link](); })
.then(data => setUsers(data))
.catch(err => setError([Link]))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <ul>{[Link](u=><li key={[Link]}>{[Link]}</li>)}</ul>;
}
● Axios
Axios — third-party HTTP client. Auto JSON parse, interceptors, better error handling than fetch. Install: npm i axios
import axios from 'axios';
// GET
const { data } = await [Link]('/api/users');
// POST
await [Link]('/api/users', { name: 'Alice' });
// Axios instance with base URL
const api = [Link]({ baseURL: '[Link]
headers: { Authorization: `Bearer ${token}` } });
// Interceptor for auth token
[Link](config => {
[Link] = `Bearer ${[Link]('token')}`;
return config;
});
● React Router v6
Client-side routing. Install: npm i react-router-dom
import { BrowserRouter, Routes, Route, Link, useNavigate, useParams } from 'react-router-dom';
// Setup
<BrowserRouter>
<Routes>
<Route path='/' element={<Home/>} />
<Route path='/user/:id' element={<User/>} />
<Route path='*' element={<NotFound/>} />
</Routes>
</BrowserRouter>
// Link (no page reload)
<Link to='/about'>About</Link>
// Programmatic navigation
const navigate = useNavigate(); navigate('/dashboard');
// URL params
const { id } = useParams();
● CRUD Operations
// CREATE
await [Link]('/api/items', newItem); setItems([...items, newItem]);
// READ
const { data } = await [Link]('/api/items'); setItems(data);
// UPDATE
await [Link](`/api/items/${id}`, updated);
setItems([Link](i => [Link]===id ? updated : i));
// DELETE
await [Link](`/api/items/${id}`);
setItems([Link](i => [Link] !== id));
● Lifting State Up
[Link] Revision Guide · Page 9
When two sibling components need shared state — lift it to their common parent. Parent holds state, passes down via props + setter
callbacks.
function Parent() {
const [val, setVal] = useState('');
return <><InputChild onChange={setVal}/><DisplayChild val={val}/></>;
}
[Link] Revision Guide · Page 10
7 State Management
● Context API
Context — React's built-in way to share data globally without prop-drilling. Best for: themes, auth, language, user data.
// 1. Create context
const AuthContext = createContext(null);
// 2. Provider — wrap at top level
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
return <[Link] value={{user, setUser}}>
{children}
</[Link]>;
}
// 3. Consume with useContext
function Navbar() {
const { user } = useContext(AuthContext);
return <div>Welcome {user?.name}</div>;
}
● Redux Toolkit
RTK is the modern, recommended way to use Redux. Reduces boilerplate drastically. Key concepts: store, slice, dispatch,
selector.
// 1. Create slice
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { [Link]++; }, // Immer handles immutability
decrement: state => { [Link]--; },
setValue: (state, action) => { [Link] = [Link]; }
}
});
export const { increment, decrement, setValue } = [Link];
export default [Link];
// 2. Configure store
import { configureStore } from '@reduxjs/toolkit';
export const store = configureStore({
reducer: { counter: counterReducer }
});
// 3. Provide store
<Provider store={store}><App /></Provider>
// 4. Use in component
const count = useSelector(state => [Link]);
const dispatch = useDispatch();
<button onClick={() => dispatch(increment())}>+</button>
RTK Query — built-in data fetching layer in RTK. Auto caching, loading/error states. Replaces most manual useEffect fetch patterns.
[Link] Revision Guide · Page 11
8 Auth, Performance & Advanced
● JWT Basics
JSON Web Token — stateless authentication. Structure: [Link] (Base64). Server signs token with secret,
client sends it in every request via Authorization header.
// Login — receive token
const { data } = await [Link]('/auth/login', creds);
[Link]('token', [Link]);
// Protected request
[Link]['Authorization'] = `Bearer ${token}`;
// Token payload (decode, don't verify in frontend)
const payload = [Link](atob([Link]('.')[1]));
// Logout
[Link]('token'); delete [Link]['Authorization'];
● Protected Routes
function ProtectedRoute({ children }) {
const token = [Link]('token');
return token ? children : <Navigate to='/login' replace />;
}
// Usage
<Route path='/dashboard' element={
<ProtectedRoute><Dashboard /></ProtectedRoute>
} />
● Performance Optimization
■ [Link]
Wraps component — skips re-render if props unchanged
export default [Link](MyComp);
■ useMemo
Memoize expensive computed value
const result = useMemo(() => heavyCalc(data), [data]);
■ useCallback
Memoize callback function
const fn = useCallback(() => handler(id), [id]);
■ Code Splitting
Lazy load components
const Page = lazy(() => import('./Page')); <Suspense fallback={<Spinner/>}><Page/></Suspense>
■ Key prop
Stable keys prevent unnecessary re-renders
key={[Link]} // never use index for dynamic lists
● Error Handling
Error Boundaries — catch JS errors in component tree (class component feature).
class ErrorBoundary extends [Link] {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
componentDidCatch(err, info) { logError(err, info); }
render() {
return [Link] ? <h2>Something went wrong</h2> : [Link];
}
}
// Wrap sections
<ErrorBoundary><UserProfile /></ErrorBoundary>
● Environment Variables
In CRA: prefix with REACT_APP_. In Vite: prefix with VITE_. Never expose secrets in frontend code.
[Link] Revision Guide · Page 12
# .env file
REACT_APP_API_URL=[Link]
VITE_API_URL=[Link]
# Access in code
[Link].REACT_APP_API_URL // CRA
[Link].VITE_API_URL // Vite
# .[Link] — override locally, gitignored
# Never commit .env files with secrets to git!
[Link] Revision Guide · Page 13
✦ Super Cheat Sheet
Everything you need — last 15 minutes before the interview
JS Essentials React Basics Router v6
var/let/const: var=func, let/const=block JSX rule: className, htmlFor, {} for JS BrowserRouter wraps entire app
Truthy/Falsy: Falsy: false 0 '' null undef NaN Fragment: <> or Routes + Route path='' element={}
Arrow fn: (a,b) => a+b Key: stable unique ID, not index Link to='/path' — no page reload
useNavigate() → navigate('/path')
Spread: {...obj, key:val} Props: read-only, parent→child
useParams() → { id }
Destruct: const {a,b}=obj [x,y]=arr State: mutable, setter triggers re-render
useLocation() → { pathname, search }
Optional ?.: obj?.prop?.method?.() setState: setX(prev => newVal) for async safety
Nullish ??: val ?? 'default'
Redux Toolkit
Hooks Quick Ref createSlice → actions + reducer
Array Methods useState(init) → [val, setter]
configureStore({ reducer: {} })
map / filter / reduce useEffect(fn, [deps])
useSelector(state => state.x.y)
find / findIndex / some / every useRef(init) → .current
const dispatch = useDispatch()
flat / flatMap / includes useMemo(fn, [deps]) → value
Immer: mutate state directly in slice
slice (no mutate) / splice (mutates) useCallback(fn, [deps]) → fn
[...arr] spread clone useContext(Context) → value Auth / JWT
useReducer(reducer, init) → [state, JWT: [Link]
Async
dispatch] Store: [Link]('token', t)
Promise: new Promise((res,rej)=>{})
Combinators: all allSettled race any
Hook Rules Header: Authorization: Bearer
Rule 1: Top level only — no loops/if Protected: token ? children :
async/await: always try/catch
Fetch: fetch(url).then(r=>[Link]())
Rule 2: React functions / custom hooks only Performance
Custom: fn name starts with 'use' memo: skip re-render if props same
useMemo: memoize heavy computation
useCallback: stable fn reference
lazy+Suspense: code split routes
Context API: createContext → Provider(value) → useContext · Error Boundary: getDerivedStateFromError + componentDidCatch · Env: REACT_APP_ (CRA) |
VITE_ (Vite) · Virtual DOM → Reconciliation → Fiber → commit phase
[Link] Revision Guide · Page 14