Movatterモバイル変換


[0]ホーム

URL:


We want to hear from you!Take our 2021 Community Survey!
This site is no longer updated.Go to react.dev

React Top-Level API

React is the entry point to the React library. If you load React from a<script> tag, these top-level APIs are available on theReact global. If you use ES6 with npm, you can writeimport React from 'react'. If you use ES5 with npm, you can writevar React = require('react').

Overview

Components

React components let you split the UI into independent, reusable pieces, and think about each piece in isolation. React components can be defined by subclassingReact.Component orReact.PureComponent.

If you don’t use ES6 classes, you may use thecreate-react-class module instead. SeeUsing React without ES6 for more information.

React components can also be defined as functions which can be wrapped:

Creating React Elements

We recommendusing JSX to describe what your UI should look like. Each JSX element is just syntactic sugar for callingReact.createElement(). You will not typically invoke the following methods directly if you are using JSX.

SeeUsing React without JSX for more information.

Transforming Elements

React provides several APIs for manipulating elements:

Fragments

React also provides a component for rendering multiple elements without a wrapper.

Refs

Suspense

Suspense lets components “wait” for something before rendering. Today, Suspense only supports one use case:loading components dynamically withReact.lazy. In the future, it will support other use cases like data fetching.

Transitions

Transitions are a new concurrent feature introduced in React 18. They allow you to mark updates as transitions, which tells React that they can be interrupted and avoid going back to Suspense fallbacks for already visible content.

Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks have adedicated docs section and a separate API reference:


Reference

React.Component

This content is out of date.

Read the new React documentation forComponent.

React.Component is the base class for React components when they are defined usingES6 classes:

classGreetingextendsReact.Component{render(){return<h1>Hello,{this.props.name}</h1>;}}

See theReact.Component API Reference for a list of methods and properties related to the baseReact.Component class.


React.PureComponent

This content is out of date.

Read the new React documentation forPureComponent.

React.PureComponent is similar toReact.Component. The difference between them is thatReact.Component doesn’t implementshouldComponentUpdate(), butReact.PureComponent implements it with a shallow prop and state comparison.

If your React component’srender() function renders the same result given the same props and state, you can useReact.PureComponent for a performance boost in some cases.

Note

React.PureComponent’sshouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extendPureComponent when you expect to have simple props and state, or useforceUpdate() when you know deep data structures have changed. Or, consider usingimmutable objects to facilitate fast comparisons of nested data.

Furthermore,React.PureComponent’sshouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.


React.memo

This content is out of date.

Read the new React documentation formemo.

const MyComponent= React.memo(functionMyComponent(props){/* render using props */});

React.memo is ahigher order component.

If your component renders the same result given the same props, you can wrap it in a call toReact.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.

React.memo only checks for prop changes. If your function component wrapped inReact.memo has auseState,useReducer oruseContext Hook in its implementation, it will still rerender when state or context change.

By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.

functionMyComponent(props){/* render using props */}functionareEqual(prevProps, nextProps){/*  return true if passing nextProps to render would return  the same result as passing prevProps to render,  otherwise return false  */}exportdefault React.memo(MyComponent, areEqual);

This method only exists as aperformance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.

Note

Unlike theshouldComponentUpdate() method on class components, theareEqual function returnstrue if the props are equal andfalse if the props are not equal. This is the inverse fromshouldComponentUpdate.


createElement()

This content is out of date.

Read the new React documentation forcreateElement.

React.createElement(  type,[props],[...children])

Create and return a newReact element of the given type. The type argument can be either a tag name string (such as'div' or'span'), aReact component type (a class or a function), or aReact fragment type.

Code written withJSX will be converted to useReact.createElement(). You will not typically invokeReact.createElement() directly if you are using JSX. SeeReact Without JSX to learn more.


cloneElement()

This content is out of date.

Read the new React documentation forcloneElement.

React.cloneElement(  element,  [config],  [...children])

Clone and return a new React element usingelement as the starting point.config should contain all new props,key, orref. The resulting element will have the original element’s props with the new props merged in shallowly. New children will replace existing children.key andref from the original element will be preserved if nokey andref present in theconfig.

React.cloneElement() is almost equivalent to:

<element.type{...element.props}{...props}>{children}</element.type>

However, it also preservesrefs. This means that if you get a child with aref on it, you won’t accidentally steal it from your ancestor. You will get the sameref attached to your new element. The newref orkey will replace old ones if present.

This API was introduced as a replacement of the deprecatedReact.addons.cloneWithProps().


createFactory()

This content is out of date.

Read the new React documentation forcreateFactory.

React.createFactory(type)

Return a function that produces React elements of a given type. LikeReact.createElement(), the type argument can be either a tag name string (such as'div' or'span'), aReact component type (a class or a function), or aReact fragment type.

This helper is considered legacy, and we encourage you to either use JSX or useReact.createElement() directly instead.

You will not typically invokeReact.createFactory() directly if you are using JSX. SeeReact Without JSX to learn more.


isValidElement()

This content is out of date.

Read the new React documentation forisValidElement.

React.isValidElement(object)

Verifies the object is a React element. Returnstrue orfalse.


React.Children

This content is out of date.

Read the new React documentation forChildren.

React.Children provides utilities for dealing with thethis.props.children opaque data structure.

React.Children.map

React.Children.map(children,function[(thisArg)])

Invokes a function on every immediate child contained withinchildren withthis set tothisArg. Ifchildren is an array it will be traversed and the function will be called for each child in the array. If children isnull orundefined, this method will returnnull orundefined rather than an array.

Note

Ifchildren is aFragment it will be treated as a single child and not traversed.

React.Children.forEach

React.Children.forEach(children,function[(thisArg)])

LikeReact.Children.map() but does not return an array.

React.Children.count

React.Children.count(children)

Returns the total number of components inchildren, equal to the number of times that a callback passed tomap orforEach would be invoked.

React.Children.only

React.Children.only(children)

Verifies thatchildren has only one child (a React element) and returns it. Otherwise this method throws an error.

Note:

React.Children.only() does not accept the return value ofReact.Children.map() because it is an array rather than a React element.

React.Children.toArray

React.Children.toArray(children)

Returns thechildren opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slicethis.props.children before passing it down.

Note:

React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is,toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.


React.Fragment

This content is out of date.

Read the new React documentation forFragment.

TheReact.Fragment component lets you return multiple elements in arender() method without creating an additional DOM element:

render(){return(<React.Fragment>      Some text.<h2>A heading</h2></React.Fragment>);}

You can also use it with the shorthand<></> syntax. For more information, seeReact v16.2.0: Improved Support for Fragments.

React.createRef

This content is out of date.

Read the new React documentation forcreateRef.

React.createRef creates aref that can be attached to React elements via the ref attribute.

classMyComponentextendsReact.Component{constructor(props){super(props);this.inputRef= React.createRef();}render(){return<inputtype="text"ref={this.inputRef}/>;}componentDidMount(){this.inputRef.current.focus();}}

React.forwardRef

This content is out of date.

Read the new React documentation forforwardRef.

React.forwardRef creates a React component that forwards theref attribute it receives to another component below in the tree. This technique is not very common but is particularly useful in two scenarios:

React.forwardRef accepts a rendering function as an argument. React will call this function withprops andref as two arguments. This function should return a React node.

const FancyButton= React.forwardRef((props, ref)=>(<buttonref={ref}className="FancyButton">{props.children}</button>));// You can now get a ref directly to the DOM button:const ref= React.createRef();<FancyButtonref={ref}>Click me!</FancyButton>;

In the above example, React passes aref given to<FancyButton ref={ref}> element as a second argument to the rendering function inside theReact.forwardRef call. This rendering function passes theref to the<button ref={ref}> element.

As a result, after React attaches the ref,ref.current will point directly to the<button> DOM element instance.

For more information, seeforwarding refs.

React.lazy

This content is out of date.

Read the new React documentation forlazy.

React.lazy() lets you define a component that is loaded dynamically. This helps reduce the bundle size to delay loading components that aren’t used during the initial render.

You can learn how to use it from ourcode splitting documentation. You might also want to check outthis article explaining how to use it in more detail.

// This component is loaded dynamicallyconst SomeComponent= React.lazy(()=>import('./SomeComponent'));

Note that renderinglazy components requires that there’s a<React.Suspense> component higher in the rendering tree. This is how you specify a loading indicator.

React.Suspense

This content is out of date.

Read the new React documentation forSuspense.

React.Suspense lets you specify the loading indicator in case some components in the tree below it are not yet ready to render. In the future we plan to letSuspense handle more scenarios such as data fetching. You can read about this inour roadmap.

Today, lazy loading components is theonly use case supported by<React.Suspense>:

// This component is loaded dynamicallyconst OtherComponent= React.lazy(()=>import('./OtherComponent'));functionMyComponent(){return(// Displays <Spinner> until OtherComponent loads<React.Suspensefallback={<Spinner/>}><div><OtherComponent/></div></React.Suspense>);}

It is documented in ourcode splitting guide. Note thatlazy components can be deep inside theSuspense tree — it doesn’t have to wrap every one of them. The best practice is to place<Suspense> where you want to see a loading indicator, but to uselazy() wherever you want to do code splitting.

Note

For content that is already shown to the user, switching back to a loading indicator can be disorienting. It is sometimes better to show the “old” UI while the new UI is being prepared. To do this, you can use the new transition APIsstartTransition anduseTransition to mark updates as transitions and avoid unexpected fallbacks.

React.Suspense in Server Side Rendering

During server side rendering Suspense Boundaries allow you to flush your application in smaller chunks by suspending.When a component suspends we schedule a low priority task to render the closest Suspense boundary’s fallback. If the component unsuspends before we flush the fallback then we send down the actual content and throw away the fallback.

React.Suspense during hydration

Suspense boundaries depend on their parent boundaries being hydrated before they can hydrate, but they can hydrate independently from sibling boundaries. Events on a boundary before it is hydrated will cause the boundary to hydrate at a higher priority than neighboring boundaries.Read more

React.startTransition

This content is out of date.

Read the new React documentation forstartTransition.

React.startTransition(callback)

React.startTransition lets you mark updates inside the provided callback as transitions. This method is designed to be used whenReact.useTransition is not available.

Note:

Updates in a transition yield to more urgent updates such as clicks.

Updates in a transition will not show a fallback for re-suspended content, allowing the user to continue interacting while rendering the update.

React.startTransition does not provide anisPending flag. To track the pending status of a transition seeReact.useTransition.

Is this page useful?Edit this page

[8]ページ先頭

©2009-2025 Movatter.jp