Table of Content
๐ Getting Started
import React from 'react';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
๐ก TIP
Always wrap your root component inside StrictMode
during development to catch potential issues early.
โ๏ธ JSX
const element = <h1>Hello, world!</h1>;
- JSX is a syntax extension that looks like HTML, used to describe UI in React.
- JSX is transpiled to
React.createElement()
calls under the hood. - Expressions like
{1 + 2}
or{props.name}
can be embedded inside JSX.
๐ก NOTE
JSX must return a single parent element. Use fragments (<>...</>
) if needed.
๐งฑ Components and Props
Components are the building blocks of a React application. Each component represents a part of the user interface.
๐ง Functional Components
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const App = () => <Welcome name="Imtiyaz" />;
๐ก TIP
Always use functional components with hooks for simplicity and performance.
๐ Destructuring Props
const Welcome = ({ name }) => <h1>Hello, {name}</h1>;
๐งฉ Default Props
const Greeting = ({ name = 'Guest' }) => <p>Hello, {name}</p>;
๐ฌ TIP
Use default props to avoid errors from undefined values.
๐ฆ Passing Children
const Card = ({ children }) => <div className="card">{children}</div>;
<Card><p>Content</p></Card>
๐ PropTypes
import PropTypes from 'prop-types';
MyComponent.propTypes = {
message: PropTypes.string
};
๐ฃ React Hooks
Hooks allow you to use state and lifecycle features in functional components.
๐ง useState
const [count, setCount] = useState(0);
- Manages state in functional components.
- Useful for counters, toggles, form inputs, etc.
๐ useEffect
useEffect(() => {
console.log("Component mounted or updated");
}, [dependencies]);
- Used for side effects like API calls, subscriptions, and timeouts.
โ ๏ธ NOTE
Cleanup functions can be returned inside useEffect
.
๐งต useContext
const value = useContext(MyContext);
- Share global data (auth, theme, locale) across components.
- Avoids prop drilling.
๐ช useRef
const inputRef = useRef();
<input ref={inputRef} />;
- Mutable value that persists across renders.
- Common for focusing inputs or triggering DOM events.
โ๏ธ useReducer
const reducer = (state, action) => {
switch(action.type) {
case 'increment': return { count: state.count + 1 };
default: return state;
}
};
const [state, dispatch] = useReducer(reducer, { count: 0 });
- Alternative to
useState
for complex logic or multiple state transitions.
๐ง useMemo
const memoized = useMemo(() => computeHeavy(val), [val]);
- Prevents recalculating expensive computations on every render.
๐ useCallback
const handleClick = useCallback(() => doSomething(), []);
- Returns memoized version of a callback function.
๐งฉ Custom Hooks
function useToggle(initial = false) {
const [state, setState] = useState(initial);
const toggle = () => setState(s => !s);
return [state, toggle];
}
๐ TIP
Prefix custom hook names with "use" so React can handle them properly.
๐ช useId
const id = useId();
<label htmlFor={id}>Name</label>
<input id={id} />
- Generates unique IDs that are consistent across the server and client.
๐งฎ useDeferredValue
const deferredValue = useDeferredValue(inputValue);
- Defers re-rendering of non-urgent updates for better performance.
๐ useTransition
const [isPending, startTransition] = useTransition();
- Lets you mark updates as non-urgent.
- Improves responsiveness for transitions.
๐ก useSyncExternalStore
const snap = useSyncExternalStore(subscribe, getSnapshot);
- Used for subscribing to external stores in a consistent way.
๐ช useLayoutEffect
useLayoutEffect(() => {
// Read DOM or apply sync layout changes
}, []);
- Similar to
useEffect
, but Runs after DOM mutations but before the browser paints - Can block painting if heavy โ use carefully to avoid jank
- Affects performance more than useEffect if misused
๐งต useInsertionEffect
useInsertionEffect(() => {
// Insert styles before layout and paint
}, []);
- Runs before any DOM mutations, even before useLayoutEffect
- Allows injecting styles into the DOM before rendering
๐ง Event Handling
๐ฑ Basic Event
function handleClick() {
alert('Clicked!');
}
<button onClick={handleClick}>Click Me</button>
๐ฏ Event Object
<input onChange={(e) => console.log(e.target.value)} />
โ Prevent Default
<form onSubmit={(e) => e.preventDefault()}>...</form>
๐ก TIP
React uses Synthetic Events, which are cross-browser wrappers around native events.
๐ Conditional Rendering
โ Ternary Operator
{isLoggedIn ? <Dashboard /> : <Login />}
โ Logical AND
{isOnline && <span>Online</span>}
๐ if-else in Functions
function renderStatus() {
if (loading) return <Loading />;
if (error) return <Error />;
return <Data />;
}
๐ Lists and Keys
๐ Rendering Lists
const items = ['A', 'B'];
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
๐ Key Warning
- Keys help React identify which items have changed.
- Avoid using array index as key unless the list is static.
๐ Forms and Inputs
๐ Controlled Components
const [input, setInput] = useState('');
<input value={input} onChange={e => setInput(e.target.value)} />
๐ Uncontrolled Components
<input ref={inputRef} />
๐ค Handling Form Submission
function handleSubmit(e) {
e.preventDefault();
console.log("Submitted", input);
}
โ Basic Validation
if (input.length < 3) setError("Too short");
๐งช Using Libraries
- Formik: Form state + validation
- React Hook Form: Better performance, works with uncontrolled components
๐งผ NOTE
For complex forms, prefer libraries over custom logic.
๐จ Styling
๐จ Inline Styles
<div style={{ color: 'red' }}>Hi</div>
๐งฉ CSS Modules
import styles from './App.module.css';
<div className={styles.title}></div>
๐จ Styled Components
const Button = styled.button`
background: purple;
color: white;
`;
๐ Tailwind CSS
<button className="bg-blue-500 text-white px-4 py-2">Click</button>
๐จ TIP
Use BEM or CSS Modules for scalable styles.
๐งญ Routing (React Router v6)
๐ Basic Setup
import { BrowserRouter, Routes, Route } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/about" element={<About />} />
<Link to="/about">About</Link>
</Routes>
</BrowserRouter>
๐งฌ Dynamic Route
<Route path="/user/:id" element={<User />} />
๐ useNavigate / useParams
const navigate = useNavigate();
const { id } = useParams();
๐งฉ Nested Routes
<Route path="/dashboard" element={<Dashboard />}>
<Route path="settings" element={<Settings />} />
</Route>
๐ State Management
๐งฉ Context API
const ThemeContext = React.createContext();
<ThemeContext.Provider value={value}>
<App />
</ThemeContext.Provider>
๐ Redux Toolkit
const store = configureStore({ reducer: rootReducer });
- Slices, actions, and reducers in one place
- DevTools integration
๐งช Other Libraries
- Zustand: Minimal API, easy to learn
- Jotai: Atomic design, flexible
- Recoil: Fine-grained state syncing
โก Performance Optimization
๐ง React.memo
const MemoComp = React.memo(MyComponent);
๐งฎ useMemo & useCallback
Memoize expensive values or functions.
โณ Lazy Loading
const LazyComp = React.lazy(() => import('./MyComp'));
- Wrap with
<Suspense>
for fallback UI
๐ DevTools
- React Profiler: Detect unnecessary re-renders
๐จ TIP
Minimize re-renders and use memoization for heavy components.
๐งช Testing
โ Unit Testing with RTL + Jest
render(<Button />);
expect(screen.getByText("Click Me")).toBeInTheDocument();
๐งญ Integration Testing
- Check interaction across components
๐ฆ E2E Testing
- Cypress: Fast, visual
- Playwright: Powerful automation
๐ Error Boundaries
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
return this.state.hasError ? <h1>Error</h1> : this.props.children;
}
}
โ ๏ธ Use class components for error boundaries.
๐ช Portals
ReactDOM.createPortal(<Modal />, document.body);
๐น Use for modals, tooltips, etc.
๐จ Strict Mode
<React.StrictMode>
<App />
</React.StrictMode>
๐ Dev-only checks for side effects and potential issues.
โ๏ธ React 18+ Concurrent Features
๐งต startTransition
startTransition(() => setInput(val));
๐ง Automatic Batching
Multiple state updates are batched automatically.
๐ React Server Components (RSC)
// app/page.js
export default async function Page() {
const data = await fetchData();
return <div>{data.name}</div>;
}
๐ Used in frameworks like Next.js. No client-side JS.
๐ง DevTools & Ecosystem
- React DevTools โ inspect components, state, props
- Redux DevTools โ debug Redux state changes
- Linting โ ESLint + Prettier for clean code
๐ Deployment
- Build:
npm run build
- Host: Vercel, Netlify, GitHub Pages
- Env Vars:
.env
,.env.production
๐ Resources
- react.dev
- reactjs.org (Legacy)
- React Router Docs
- usehooks.com
- GitHub: awesome-react
- react-hook-form.com
- github.com/streamich/react-use
โ TIP
Stick to functional components and master hooks โ thatโs where modern React is headed.
๐งผ NOTE
Donโt reinvent the wheel. Use community libraries when possible (e.g., react-hook-form
, react-query
, zustand
).
Comments
Leave a Comment