React is the popular JavaScript library for building component-based user interfaces.
Function Components & JSX
import React, { useState } from 'react';
export function Greeting({ name, role = "Member" }) {
return (
<div className="card">
<h2>Hello, {name}!</h2>
<span className="badge">{role}</span>
</div>
);
}
Core Hooks
useState
const [count, setCount] = useState(0);
// Functional state update (guarantees latest state)
setCount((prev) => prev + 1);
useEffect
Handles side-effects like data fetching, subscriptions, and DOM mutations:
useEffect(() => {
const handleResize = () => setWindowWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
// Cleanup function runs on unmount or before effect re-runs
return () => {
window.removeEventListener('resize', handleResize);
};
}, []); // Empty dependency array runs once on mount
useContext
Consumes context without prop-drilling:
const ThemeContext = React.createContext('light');
function Display() {
const theme = useContext(ThemeContext);
return <div className={`theme-${theme}`}>Active Theme</div>;
}
useMemo & useCallback
Performance optimizations for expensive calculations and referential equality:
// Memoize expensive calculation
const filteredUsers = useMemo(() => {
return users.filter((u) => u.score > threshold);
}, [users, threshold]);
// Memoize callback function definition
const handleRemove = useCallback((id) => {
setItems((prev) => prev.filter((item) => item.id !== id));
}, []);
useRef
Stores mutable values across renders without triggering a re-render:
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return <input ref={inputRef} />;
Custom Hooks
Extract reusable stateful logic into custom hook functions prefixed with use:
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOnline;
}
Portals & Fragments
// Fragments without extra wrapper elements
return (
<>
<Header />
<MainContent />
</>
);
// Rendering into external DOM container
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal-overlay">{children}</div>,
document.getElementById('modal-root')
);
}