React Reference Manual
The React manual contains various core APIs, Hooks, component lifecycle methods, and more.
The following is a complete React reference manual, covering all core concepts from basic to advanced (based on React 18+ modern practices, prioritizing function components + Hooks). Each table includesConcept/Syntax、Description、Example CodeandNotes。
1. JSX Basics
| Concept/Syntax | Description | Example Code | Notes |
|---|---|---|---|
| JSX Basic Structure | HTML-like syntax, compiled intoReact.createElement |
return <div>Hello</div>; |
Must have a single root element, can use<></>Fragment |
| Expression Embedding | use{}Embed JS expressions (only expressions, not statements) |
<h1>{name.toUpperCase()}</h1> |
Supports calculation, variables, ternary, etc. |
| Attribute Binding | class → className,for → htmlFor | <div className="box" htmlFor="id"> |
Camel case naming (e.g.tabIndex) |
| Self-closing tags | All tags must be closed | <img src="....html" alt="..." /> |
Tags without children must be self-closing |
| Conditional Rendering | Ternary operator or&& |
{isLogin ? <User /> : <Login />}<br>{count > 0 && <span>{count}</span>} |
&&Used for "render if exists" |
| List Rendering | usemap(), must addkey |
{items.map(item => <li key={item.id}>{item.name}</li>)} |
Key must be unique and stable, avoid using index |
| Comments | use{/* */} |
{/* This is a comment */} |
Placed inside JSX |
| Fragment | Empty tag, avoids extra DOM | <><p>1</p><p>2</p></>or<React.Fragment> |
Short syntax<></>More commonly used |
2. Component Basics
| Concept/Syntax | Description | Example Code | Notes |
|---|---|---|---|
| Function Components (Recommended) | Capitalize first letter, return JSX | function App() { return <div>Hello</div>; } |
Modern first choice, no this |
| Class Components (Legacy) | UseclassInheritanceReact.Component |
class App extends React.Component { render() { return <div/>; } } |
Only for understanding legacy code |
| Props Passing | One-way data flow, from parent to child | <Child name="QiXin" age={25} /><br>Child component:function Child({name}) {...} |
Read-only, cannot be modified |
| Default Props | defaultProps(Function components use parameter default values) |
function Child({name = 'Guest'}) {...} |
ES6 default parameters are more concise |
| Props Type Checking | PropTypes (or TypeScript) | Child.propTypes = { name: PropTypes.string.isRequired } |
Warning in development mode, removed in production |
| Component Composition | Nesting, children | <Card><h1>Title</h1></Card><br>Parent:{props.children} |
children is a special Prop |
3. State and Hooks (Core)
| Hook / Concept | Description | Example Code | Notes |
|---|---|---|---|
| useState | Declare State Variable | const [count, setCount] = useState(0);<br><button onClick={() => setCount(c => c+1)}> |
Functional update in set prevents stale state |
| useEffect | Side Effects (mount, update, cleanup) | useEffect(() => { ... }, [dep]);<br>Return a cleanup function |
Empty array [] runs only on mount |
| useRef | Store mutable values or DOM references | const inputRef = useRef(null);<br>inputRef.current.focus(); |
Does not trigger re-render |
| useContext | Consume Context, avoid Prop Drilling | const theme = useContext(ThemeContext); |
Works with Context.Provider |
| useReducer | Complex state logic (similar to Redux) | const [state, dispatch] = useReducer(reducer, initial); |
Used for multiple related states |
| useMemo | Cache computed results | const memoValue = useMemo(() => compute(), [dep]); |
Avoid re-executing expensive calculations |
| useCallback | Cache function references | const handle = useCallback(() => {...}, [dep]); |
Optimize child component Props |
| Custom Hooks | Encapsulate reusable logic | function useFetch(url) { ... return data; } |
Start with use |
4. Lifecycle (Class Components vs Hooks)
| Phase | Class Component Method | Hooks Equivalent | Notes |
|---|---|---|---|
| Mount | constructor → render → componentDidMount | useEffect(() => {…}, []) | Initialize state / API calls |
| Update | shouldComponentUpdate → render → componentDidUpdate | useEffect(() => {…}, [dep]) + memo | Triggered by dependency changes |
| Unmount | componentWillUnmount | useEffect returns a cleanup function | Clear timers/subscriptions |
| Error Handling | componentDidCatch | ErrorBoundary component | Hooks have no direct equivalent |
5. Context and Global State
| Concept | Description | Example Code | Notes |
|---|---|---|---|
| Context API | Global data sharing | const ThemeContext = createContext();<br><Provider value="dark"> |
Avoid overuse, performance cost |
| useContext | Consume in function components | const theme = useContext(ThemeContext); |
Concise replacement for Consumer |
6. Advanced Features (React 18+)
| Concept | Description | Example Code | Notes |
|---|---|---|---|
| Concurrent Mode | Interruptible rendering, improves responsiveness | <React.StrictMode> + Transitions |
Automatic batching of updates |
| Suspense | Lazy loading / waiting for data fetching | <Suspense fallback={<Loading/>}><LazyComp /></Suspense> |
Works with lazy |
| React.lazy | Code splitting lazy loading | const Lazy = React.lazy(() => import('./Comp')); |
Must be wrapped by Suspense |
| startTransition | Mark non-urgent updates | startTransition(() => setQuery(e.target.value)); |
Keep UI responsive |
| useDeferredValue | Defer non-urgent values | const deferred = useDeferredValue(query); |
Similar to input debounce |
7. Performance Optimization
| Technique | Description | Example Code | Notes |
|---|---|---|---|
| React.memo | Shallow compare Props, avoid unnecessary rendering | export default React.memo(Component); |
Exclusive to function components |
| useMemo / useCallback | Cache values/functions | As above | Prevent child component re-rendering |
| Key optimization | Stable and unique key | e.g., list rendering | Avoid index |
| Virtual list | Long list optimization (react-window) | <FixedSizeList height={500} itemCount={1000} /> |
Third-party library |
8. Common Ecosystem Tools
| Tool | Purpose | Installation/Usage | Notes |
|---|---|---|---|
| React Router v6 | Routing and navigation | npm i react-router-dom<br><BrowserRouter><Routes><Route path="/" element={<Home/>}/></Routes></BrowserRouter> |
Nested routes, Outlet |
| Redux Toolkit | Global state management | npm i @reduxjs/toolkit react-redux |
RTK Query data fetching |
| React Hook Form | Form handling | useForm() |
High performance, simple validation |
| Axios / Fetch | Data requests | fetch('/api') |
Used in useEffect |
| Tailwind / MUI | UI styling | npm i tailwindcssormui |
Quick beautification |
9. Debugging and Best Practices
| Item | Description | Tool/Method |
|---|---|---|
| Debugging tool | View component tree, Props, Hooks | React DevTools (browser extension) |
| Strict Mode | Discover potential issues | <React.StrictMode> |
| ESLint + Prettier | Code standards | VS Code extension |
| Testing | Jest + React Testing Library | npm i --save-dev jest |
The following are some common functions and methods, along with their brief descriptions:
React Core API
createElement(type, [props], [...children])- Create a React element or component.
Example
const element = React.createElement('div', { className: 'container' }, 'Hello, World!');
// React.createElement returns a React element
cloneElement(element, [props], [...children])- Clone and return a React element, which can be passed new props and children.
Example
const parentElement = <div>Hello</div>;
const clonedElement = cloneElement(parentElement, { className: 'child' });
// clonedElement is a cloned React element with a new className
createFactory(type)- Create a factory function for creating React elements of a specified type.
Example
const factory = React.createFactory('button');
const buttonElement = factory({ onClick: () => console.log('Button clicked') }, 'Click me');
// buttonElement is a React element created by the factory, a clickable button
isValidElement(element)- Determine whether an object is a valid React element.
Example
const element = <div>Hello</div>;
console.log(isValidElement(element)); // true
Children.map(children, function[(thisArg)])- Iterate over and map React children.
Example
const parentElement = (
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
);
const mappedChildren = Children.map(parentElement.props.children, child => (
<li>{child}</li>
));
// mappedChildren is the mapped list of children
React Component Lifecycle Methods
constructor(props)- Constructor, called when the component is created, used to initialize state and bind methods.
Example
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return <div>{this.state.count}</div>;
}
}
componentDidMount()- Called after the component is mounted, usually used for side-effect operations such as data fetching and subscriptions.
Example
class MyComponent extends Component {
componentDidMount() {
// Subscribe to data after the component is mounted
this.subscription = subscribeToData(data => {
this.setState({ data });
});
}
componentWillUnmount() {
// Unsubscribe before the component unmounts
this.subscription.unsubscribe();
}
render() {
return <div>{this.state.data}</div>;
}
}
componentDidUpdate(prevProps, prevState)- Called after the component updates, usually used to respond to changes in props or state.
Example
class MyComponent extends Component {
componentDidUpdate(prevProps, prevState) {
// Update data when props or state change
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
render() {
return <div>{this.props.userID}</div>;
}
}
componentWillUnmount()- Called before the component is unmounted, used to release resources such as cleaning up timers and unsubscribing.
Example
class MyComponent extends Component {
componentWillUnmount() {
// Clean up resources before the component unmounts
clearInterval(this.timerID);
}
render() {
return <div>{this.state.time}</div>;
}
}
static getDerivedStateFromProps(props, state)- Used to replace componentWillReceiveProps, updating state when props change.
Example
class MyComponent extends Component {
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.userID !== prevState.userID) {
return { userID: nextProps.userID };
}
return null;
}
render() {
return <div>{this.state.userID}</div>;
}
}
React Hooks
useState(initialState)- Declare a state variable and its update function.
Example
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
useEffect(callback, [dependencies])- Declare a side-effect operation, similar to a combination of componentDidMount and componentDidUpdate.
Example
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []); // An empty array as the second argument means it only runs when the component mounts and unmounts
return <p>Timer: {seconds} seconds</p>;
}
useContext(context)- Get and subscribe to a React context.
Example
const MyContext = React.createContext('default');
function MyComponent() {
const contextValue = useContext(MyContext);
return <p>Context value: {contextValue}</p>;
}
useReducer(reducer, initialState)- Declare a reducer and dispatch function for complex state logic.
Example
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
useCallback(callback, [dependencies])- Cache a callback function to avoid recreating it when dependencies change.
Example
function ParentComponent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<ChildComponent onClick={increment} />
</div>
);
}
function ChildComponent({ onClick }) {
return <button onClick={onClick}>Increment Count</button>;
}
useMemo(factory, [dependencies])- Cache a computed value to avoid recalculating it when dependencies change.
Example
function ExpensiveComponent({ data }) {
const expensiveValue = useMemo(() => {
return computeExpensiveValue(data);
}, [data]);
return <div>Expensive value: {expensiveValue}</div>;
}
useRef(initialValue)- Create a persistent reference that can be used to access DOM elements or cache any mutable value.
Example
function TextInputWithFocusButton() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<>
<input ref={inputRef} type="text" />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</>
);
}
Other Common Functions
ReactDOM.render(element, container[, callback])- Render a React element to the specified DOM node.
Example
import ReactDOM from 'react-dom';
const element = <h1>Hello, World!</h1>;
ReactDOM.render(element, document.getElementById('root'));
ReactDOM.createRoot(container[, options])- Create a React root instance, supporting concurrent rendering features.
Example
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
ReactDOM.unmountComponentAtNode(container)- Unmount the React component on the specified DOM node.
Example
import ReactDOM from 'react-dom';
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
ReactDOMServer.renderToString(element)- Render a React element to a static HTML string for server-side rendering.
Example
import ReactDOMServer from 'react-dom/server';
const element = <div>Hello, World!</div>;
const htmlString = ReactDOMServer.renderToString(element);