Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

React Reference Manual

React Reference Manual

The React manual covers 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 modern React 18+ practices, prioritizing function components + Hooks). Each table containsConcept/Syntax、Description、Example Code and Notes。

1. JSX Fundamentals

Concept/Syntax Description Example Code Notes
JSX basic structure HTML-like syntax, compiled into React.createElement return
Hello
;
Must have a single root element; you can use <> Fragment
Embedding expressions Using {} to embed JS expressions (expressions only, not statements)

{name.toUpperCase()}

Supports calculations, variables, ternaries, etc.
Attribute Binding class → className,for → htmlFor
CamelCase naming (such as tabIndex)
Self-closing tags All tags must be closed ... Tags without children must be self-closing
Conditional Rendering Ternary operator or && {isLogin ? : }
{count > 0 && {count}}
&& for "render if present"
List Rendering Using map(), must add key {items.map(item =>
  • {item.name}
  • )}
    key must be unique and stable; avoid using index
    Notes Using {/* */} {/* 这是一个注释 */} placed inside JSX
    Fragment Empty tag, avoids extra DOM <>

    1

    2

    or
    Shorthand syntax <> More commonly used

    2. Component Fundamentals

    Concept/Syntax Description Example Code Notes
    Function components (recommended) Capitalized first letter, returns JSX function App() { return
    Hello
    ; }
    Modern preferred choice, no this
    Class components (legacy) Use class inheritance React.Component class App extends React.Component { render() { return
    ; } }
    Only for understanding legacy code
    Props passing Unidirectional data flow, from parent to child
    Child component:function Child({name}) {...}
    Read-only, cannot be modified
    Default Props defaultProps(function components use default parameter values) function Child({name = 'Guest'}) {...} ES6 default parameters are more concise
    Props type checking PropTypes (or TypeScript) Child.propTypes = { name: PropTypes.string.isRequired } Warnings in development mode, removed in production
    Component composition Nesting, children

    Title


    Parent:{props.children}
    children is a special prop

    3. State and Hooks (Core)

    Hook / Concept Description Example Code Notes
    useState Declare state variables const [count, setCount] = useState(0);
    set functional updates avoid stale state
    useEffect Side effects (mount, update, cleanup) useEffect(() => { ... }, [dep]);
    Return a cleanup function
    Empty array [] mounts only once
    useRef Store mutable values or DOM references const inputRef = useRef(null);
    inputRef.current.focus();
    Does not trigger re-rendering
    useContext Consume Context, avoid prop drilling const theme = useContext(ThemeContext); Used together with Context.Provider
    useReducer Complex state logic (similar to Redux) const [state, dispatch] = useReducer(reducer, initial); For multiple related states
    useMemo Cache computed results const memoValue = useMemo(() => compute(), [dep]); Avoid re-running expensive calculations
    useCallback Cache function references const handle = useCallback(() => {...}, [dep]); Optimize child component props
    Custom Hooks Encapsulate reusable logic function useFetch(url) { ... return data; } Starts with use

    4. Lifecycle (Class Components vs Hooks)

    Stage Class component methods 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 No direct Hooks equivalent

    5. Context and Global State

    Concept Description Example Code Notes
    Context API Global data sharing const ThemeContext = createContext();
    Avoid overuse; performance cost
    useContext Consume in function components const theme = useContext(ThemeContext); Concise alternative to Consumer

    6. Advanced Features (React 18+)

    Concept Description Example Code Notes
    Concurrent Mode Interruptible rendering, improved responsiveness + Transitions Automatic batching of updates
    Suspense Lazy loading / data fetching wait }> Used together with lazy
    React.lazy Code splitting and lazy loading const Lazy = React.lazy(() => import('./Comp')); Needs to be wrapped in Suspense
    startTransition Mark non-urgent updates startTransition(() => setQuery(e.target.value)); Keep the UI responsive
    useDeferredValue Defer non-urgent values const deferred = useDeferredValue(query); Similar to input debouncing

    7. Performance Optimization

    Tip Description Example Code Notes
    React.memo Shallow compare props to avoid unnecessary renders export default React.memo(Component); For function components only
    useMemo / useCallback Cache values / functions As above Prevent child components from re-rendering
    Key optimization Stable, unique key Such as list rendering Avoid index
    Virtual list Long list optimization (react-window) Third-party library

    8. Common Ecosystem Tools

    Tool Purpose Installation / Usage Notes
    React Router v6 Route Navigation npm i react-router-dom
    }/>
    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 Fetching fetch('/api') Used inside useEffect
    Tailwind / MUI UI styling npm i tailwindcss or mui Quick beautification

    9. Debugging and Best Practices

    Projects Description Tool / Method
    Debugging tools Inspect component tree, props, Hooks React DevTools (browser extension)
    Strict Mode Discover potential issues
    ESLint + Prettier Code Standards VS Code plugin
    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]) - Creates a React element or component.

    Example

    import

    React from

    'react'

    ;

    const

    element

    =

    React.

    createElement

    (

    'div'

    ,

    {

    className

    :

    'container'

    }

    ,

    'Hello, World!'

    )

    ;

    // React.createElement returns a React element

    cloneElement(element, [props], [...children]) - Clones and returns a React element, allowing new props and children to be passed.

    Example

    import

    React

    ,

    {

    cloneElement

    }

    from

    'react'

    ;

    const

    parentElement

    =

    <
    div
    Hello
    div

    ;

    const

    clonedElement

    =

    cloneElement

    (

    parentElement

    ,

    {

    className

    :

    'child'

    }

    )

    ;

    // clonedElement is a cloned React element with a new className

    createFactory(type) - Creates a factory function for creating React elements of a specified type.

    Example

    import

    React from

    'react'

    ;

    const

    factory

    =

    React.

    createFactory

    (

    'button'

    )

    ;

    const

    buttonElement

    =

    factory

    (

    {

    onClick

    :

    (

    )

    =>

    console.

    log

    (

    'Button clicked'

    )

    }

    ,

    'Click me'

    )

    ;

    // buttonElement is a React element created by a factory, a clickable button

    isValidElement(element) - Determines whether an object is a valid React element.

    Example

    import

    React

    ,

    {

    isValidElement

    }

    from

    'react'

    ;

    const

    element

    =

    <
    div
    Hello
    div

    ;

    console.

    log

    (

    isValidElement

    (

    element

    )

    )

    ;

    // true

    Children.map(children, function[(thisArg)]) - Iterates over and maps React children.

    Example

    import

    React

    ,

    {

    Children

    }

    from

    'react'

    ;

    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 list of mapped children

    React Component Lifecycle Methods

    constructor(props) - The constructor, called when a component is created, used to initialize state and bind methods.

    Example

    import

    React

    ,

    {

    Component

    }

    from

    'react'

    ;

    class

    MyComponent

    extends

    Component

    {

      constructor

    (

    props

    )

    {

       

    super

    (

    props

    )

    ;

       

    this

    .

    state

    =

    {

          count

    :

    0

       

    }

    ;

     

    }

      render

    (

    )

    {

       

    return

    <
    div
    {
    this

    .

    state

    .

    count

    }

    div

    ;

     

    }

    }

    componentDidMount() - Called after a component is mounted, typically used for side effects such as data fetching and subscriptions.

    Example

    import

    React

    ,

    {

    Component

    }

    from

    'react'

    ;

    class

    MyComponent

    extends

    Component

    {

      componentDidMount

    (

    )

    {

       

    // Subscribe to data after the component mounts

       

    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 a component updates, typically used to respond to changes in props or state.

    Example

    import

    React

    ,

    {

    Component

    }

    from

    'react'

    ;

    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 a component is unmounted, used to clean up timers, cancel subscriptions, and release other resources.

    Example

    import

    React

    ,

    {

    Component

    }

    from

    'react'

    ;

    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

    import

    React

    ,

    {

    Component

    }

    from

    'react'

    ;

    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) - Declares a state variable and its update function.

    Example

    import

    React

    ,

    {

    useState

    }

    from

    'react'

    ;

    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]) - Declares a side effect operation, similar to a combination of componentDidMount and componentDidUpdate.

    Example

    import

    React

    ,

    {

    useState

    ,

    useEffect

    }

    from

    'react'

    ;

    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 parameter means it runs only on mount and unmount

     

    return

    <
    p
    Timer

    :

    {

    seconds

    }

    seconds

    p

    ;

    }

    useContext(context) - Gets and subscribes to a React context.

    Example

    import

    React

    ,

    {

    useContext

    }

    from

    'react'

    ;

    const

    MyContext

    =

    React.

    createContext

    (

    'default'

    )

    ;

    function

    MyComponent

    (

    )

    {

     

    const

    contextValue

    =

    useContext

    (

    MyContext

    )

    ;

     

    return

    <

    p

    Context value

    :

    {

    contextValue

    }

    p

    ;

    }

    useReducer(reducer, initialState) - Declares a reducer and dispatch function for complex state logic.

    Example

    import

    React

    ,

    {

    useReducer

    }

    from

    'react'

    ;

    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]) - Memoizes a callback function to avoid re-creation when dependencies change.

    Example

    import

    React

    ,

    {

    useState

    ,

    useCallback

    }

    from

    'react'

    ;

    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]) - Memoizes a computed value to avoid re-computation when dependencies change.

    Example

    import

    React

    ,

    {

    useMemo

    }

    from

    'react'

    ;

    function

    ExpensiveComponent

    (

    {

    data

    }

    )

    {

     

    const

    expensiveValue

    =

    useMemo

    (

    (

    )

    =>

    {

       

    return

    computeExpensiveValue

    (

    data

    )

    ;

     

    }

    ,

    [

    data

    ]

    )

    ;

     

    return

    <

    div

    Expensive value

    :

    {

    expensiveValue

    }

    div

    ;

    }

    useRef(initialValue) - Creates a persistent reference that can be used to access DOM elements or cache any mutable value.

    Example

    import

    React

    ,

    {

    useRef

    ,

    useEffect

    }

    from

    'react'

    ;

    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]) - Renders a React element into the specified DOM node.

    Example

    import

    React from

    'react'

    ;

    import

    ReactDOM from

    'react-dom'

    ;

    const

    element

    =

    <
    h1
    Hello
    ,
    World

    !

    h1

    ;

    ReactDOM.

    render

    (

    element

    ,

    document.

    getElementById

    (

    'root'

    )

    )

    ;

    ReactDOM.createRoot(container[, options]) - Creates a React root instance with support for concurrent rendering features.

    Example

    import

    ReactDOM from

    'react-dom'

    ;

    const

    root

    =

    ReactDOM.

    createRoot

    (

    document.

    getElementById

    (

    'root'

    )

    )

    ;

    root.

    render

    (

    <
    App
    />
    )

    ;

    ReactDOM.unmountComponentAtNode(container) - Unmounts a React component from the specified DOM node.

    Example

    import

    React from

    'react'

    ;

    import

    ReactDOM from

    'react-dom'

    ;

    ReactDOM.

    unmountComponentAtNode

    (

    document.

    getElementById

    (

    'root'

    )

    )

    ;

    ReactDOMServer.renderToString(element) - Renders a React element to a static HTML string for server-side rendering.

    Example

    import

    React from

    'react'

    ;

    import

    ReactDOMServer from

    'react-dom/server'

    ;

    const

    element

    =

    <
    div
    Hello
    ,
    World

    !

    div

    ;

    const

    htmlString

    =

    ReactDOMServer.

    renderToString

    (

    element

    )

    ;