Most React apps will have their files “bundled” using tools like Webpack, Rollup or Browserify. Bundling is the process of following imported files and merging them into a single file: a “bundle”. This bundle can then be included on a webpage to load an entire app at once.
Example
App:
// app.js import{ add }from'./math.js';
console.log(add(16,26));// 42
// math.js exportfunctionadd(a, b){ return a + b; }
Bundle:
functionadd(a, b){ return a + b; }
console.log(add(16,26));// 42
Note:
Your bundles will end up looking a lot different than this.
If you’re using Create React App, Next.js, Gatsby, or a similar tool, you will have a Webpack setup out of the box to bundle your app.
If you aren’t, you’ll need to set up bundling yourself. For example, see the Installation and Getting Started guides on the Webpack docs.
Code Splitting
Bundling is great, but as your app grows, your bundle will grow too. Especially if you are including large third-party libraries. You need to keep an eye on the code you are including in your bundle so that you don’t accidentally make it so large that your app takes a long time to load.
To avoid winding up with a large bundle, it’s good to get ahead of the problem and start “splitting” your bundle. Code-Splitting is a feature
supported by bundlers like Webpack, Rollup and Browserify (via factor-bundle) which can create multiple bundles that can be dynamically loaded at runtime.
Code-splitting your app can help you “lazy-load” just the things that are currently needed by the user, which can dramatically improve the performance of your app. While you haven’t reduced the overall amount of code in your app, you’ve avoided loading code that the user may never need, and reduced the amount of code needed during the initial load.
import()
The best way to introduce code-splitting into your app is through the dynamic
import()
syntax.
When Webpack comes across this syntax, it automatically starts code-splitting your app. If you’re using Create React App, this is already configured for you and you can start using it immediately. It’s also supported out of the box in Next.js.
If you’re setting up Webpack yourself, you’ll probably want to read Webpack’s guide on code splitting. Your Webpack config should look vaguely like this.
When using Babel, you’ll need to make sure that Babel can parse the dynamic import syntax but is not transforming it. For that you will need @babel/plugin-syntax-dynamic-import.
React.lazy
The
React.lazy
function lets you render a dynamic import as a regular component.
This will automatically load the bundle containing the
OtherComponent
when this component is first rendered.
React.lazy
takes a function that must call a dynamic
import()
. This must return a
Promise
which resolves to a module with a
default
export containing a React component.
The lazy component should then be rendered inside a
Suspense
component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.
The
fallback
prop accepts any React elements that you want to render while waiting for the component to load. You can place the
Suspense
component anywhere above the lazy component. You can even wrap multiple lazy components with a single
Suspense
component.
Any component may suspend as a result of rendering, even components that were already shown to the user. In order for screen content to always be consistent, if an already shown component suspends, React has to hide its tree up to the closest
<Suspense>
boundary. However, from the user’s perspective, this can be disorienting.
In this example, if tab gets changed from
'photos'
to
'comments'
, but
Comments
suspends, the user will see a glimmer. This makes sense because the user no longer wants to see
Photos
, the
Comments
component is not ready to render anything, and React needs to keep the user experience consistent, so it has no choice but to show the
Glimmer
above.
However, sometimes this user experience is not desirable. In particular, it is sometimes better to show the “old” UI while the new UI is being prepared. You can use the new
startTransition
API to make React do this:
Here, you tell React that setting tab to
'comments'
is not an urgent update, but is a transition that may take some time. React will then keep the old UI in place and interactive, and will switch to showing
<Comments />
when it is ready. See Transitions for more info.
Error boundaries
If the other module fails to load (for example, due to network failure), it will trigger an error. You can handle these errors to show a nice user experience and manage recovery with Error Boundaries. Once you’ve created your Error Boundary, you can use it anywhere above your lazy components to display an error state when there’s a network error.
Deciding where in your app to introduce code splitting can be a bit tricky. You want to make sure you choose places that will split bundles evenly, but won’t disrupt the user experience.
A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time.
Here’s an example of how to setup route-based code splitting into your app using libraries like React Router with
React.lazy
.
React.lazy
currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don’t pull in unused components.
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a “theme” prop in order to style the Button component:
functionToolbar(props){ // The Toolbar component must take an extra "theme" prop// and pass it to the ThemedButton. This can become painful// if every single button in the app needs to know the theme// because it would have to be passed through all components.return( <div> <ThemedButtontheme={props.theme}/></div> ); }
Using context, we can avoid passing props through intermediate elements:
// Context lets us pass a value deep into the component tree// without explicitly threading it through every component.// Create a context for the current theme (with "light" as the default).const ThemeContext = React.createContext('light'); classAppextendsReact.Component{ render(){ // Use a Provider to pass the current theme to the tree below.// Any component can read it, no matter how deep it is.// In this example, we're passing "dark" as the current value.return( <ThemeContext.Providervalue="dark"><Toolbar/> </ThemeContext.Provider> ); } }
// A component in the middle doesn't have to// pass the theme down explicitly anymore.functionToolbar(){ return( <div> <ThemedButton/> </div> ); }
classThemedButtonextendsReact.Component{ // Assign a contextType to read the current theme context.// React will find the closest theme Provider above and use its value.// In this example, the current theme is "dark".static contextType = ThemeContext; render(){ return<Buttontheme={this.context}/>;} }
Before You Use Context
Context is primarily used when some data needs to be accessible by
many
components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.
If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.
For example, consider a
Page
component that passes a
user
and
avatarSize
prop several levels down so that deeply nested
Link
and
Avatar
components can read it:
<Pageuser={user}avatarSize={avatarSize}/> // ... which renders ... <PageLayoutuser={user}avatarSize={avatarSize}/> // ... which renders ... <NavigationBaruser={user}avatarSize={avatarSize}/> // ... which renders ... <Linkhref={user.permalink}> <Avataruser={user}size={avatarSize}/> </Link>
It might feel redundant to pass down the
user
and
avatarSize
props through many levels if in the end only the
Avatar
component really needs it. It’s also annoying that whenever the
Avatar
component needs more props from the top, you have to add them at all the intermediate levels too.
One way to solve this issue
without context
is to pass down the
Avatar
component itself so that the intermediate components don’t need to know about the
user
or
avatarSize
props:
// Now, we have: <Pageuser={user}avatarSize={avatarSize}/> // ... which renders ... <PageLayoutuserLink={...}/> // ... which renders ... <NavigationBaruserLink={...}/> // ... which renders ... {props.userLink}
With this change, only the top-most Page component needs to know about the
Link
and
Avatar
components’ use of
user
and
avatarSize
.
This
inversion of control
can make your code cleaner in many cases by reducing the amount of props you need to pass through your application and giving more control to the root components. Such inversion, however, isn’t the right choice in every case; moving more complexity higher in the tree makes those higher-level components more complicated and forces the lower-level components to be more flexible than you may want.
You’re not limited to a single child for a component. You may pass multiple children, or even have multiple separate “slots” for children, as documented here:
This pattern is sufficient for many cases when you need to decouple a child from its immediate parents. You can take it even further with render props if the child needs to communicate with the parent before rendering.
However, sometimes the same data needs to be accessible by many components in the tree, and at different nesting levels. Context lets you “broadcast” such data, and changes to it, to all components below. Common examples where using context might be simpler than the alternatives include managing the current locale, theme, or a data cache.
Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching
Provider
above it in the tree.
The
defaultValue
argument is
only
used when a component does not have a matching Provider above it in the tree. This default value can be helpful for testing components in isolation without wrapping them. Note: passing
undefined
as a Provider value does not cause consuming components to use
defaultValue
.
Context.Provider
<MyContext.Providervalue={/* some value */}>
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
The Provider component accepts a
value
prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
All consumers that are descendants of a Provider will re-render whenever the Provider’s
value
prop changes. The propagation from Provider to its descendant consumers (including
.contextType
and
useContext
) is not subject to the
shouldComponentUpdate
method, so the consumer is updated even when an ancestor component skips an update.
Changes are determined by comparing the new and old values using the same algorithm as
Object.is
.
Note
The way changes are determined can cause some issues when passing objects as
value
: see Caveats.
Class.contextType
classMyClassextendsReact.Component{ componentDidMount(){ let value =this.context; /* perform a side-effect at mount using the value of MyContext */ } componentDidUpdate(){ let value =this.context; /* ... */ } componentWillUnmount(){ let value =this.context; /* ... */ } render(){ let value =this.context; /* render something based on the value of MyContext */ } } MyClass.contextType = MyContext;
The
contextType
property on a class can be assigned a Context object created by
React.createContext()
. Using this property lets you consume the nearest current value of that Context type using
this.context
. You can reference this in any of the lifecycle methods including the render function.
Note:
You can only subscribe to a single context using this API. If you need to read more than one see Consuming Multiple Contexts.
If you are using the experimental public class fields syntax, you can use a
static
class field to initialize your
contextType
.
classMyClassextendsReact.Component{ static contextType = MyContext; render(){ let value =this.context; /* render something based on the value */ } }
Context.Consumer
<MyContext.Consumer> {value=>/* render something based on the context value */} </MyContext.Consumer>
A React component that subscribes to context changes. Using this component lets you subscribe to a context within a function component.
Requires a function as a child. The function receives the current context value and returns a React node. The
value
argument passed to the function will be equal to the
value
prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the
value
argument will be equal to the
defaultValue
that was passed to
createContext()
.
Note
For more information about the ‘function as a child’ pattern, see render props.
Context.displayName
Context object accepts a
displayName
string property. React DevTools uses this string to determine what to display for the context.
For example, the following component will appear as MyDisplayName in the DevTools:
const MyContext = React.createContext(/* some value */); MyContext.displayName ='MyDisplayName'; <MyContext.Provider> // "MyDisplayName.Provider" in DevTools <MyContext.Consumer> // "MyDisplayName.Consumer" in DevTools
Examples
Dynamic Context
A more complex example with dynamic values for the theme:
render(){ // The ThemedButton button inside the ThemeProvider// uses the theme from state while the one outside uses// the default dark themereturn( <Page> <ThemeContext.Providervalue={this.state.theme}><ToolbarchangeTheme={this.toggleTheme}/></ThemeContext.Provider><Section> <ThemedButton/></Section> </Page> ); } }
It is often necessary to update the context from a component that is nested somewhere deeply in the component tree. In this case you can pass a function down through the context to allow consumers to update the context:
theme-context.js
// Make sure the shape of the default value passed to // createContext matches the shape that the consumers expect! exportconst ThemeContext = React.createContext({ theme: themes.dark,toggleTheme:()=>{},});
theme-toggler-button.js
import{ThemeContext}from'./theme-context';
functionThemeTogglerButton(){ // The Theme Toggler Button receives not only the theme// but also a toggleTheme function from the contextreturn( <ThemeContext.Consumer> {({theme, toggleTheme})=>(<button onClick={toggleTheme} style={{backgroundColor: theme.background}}> Toggle Theme </button> )} </ThemeContext.Consumer> ); }
// State also contains the updater function so it will// be passed down into the context providerthis.state ={ theme: themes.light, toggleTheme:this.toggleTheme,}; }
render(){ // The entire state is passed to the providerreturn( <ThemeContext.Providervalue={this.state}><Content/> </ThemeContext.Provider> ); } }
// A component may consume multiple contexts functionContent(){ return( <ThemeContext.Consumer>{theme=>(<UserContext.Consumer>{user=>(<ProfilePageuser={user}theme={theme}/>)}</UserContext.Consumer>)}</ThemeContext.Consumer>); }
If two or more context values are often used together, you might want to consider creating your own render prop component that provides both.
Caveats
Because context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders. For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for
value
:
React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in a future major React version. Read the legacy context docs here.
A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”.
Error boundaries are React components that
catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI
instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
Note
Error boundaries do
not
catch errors for:
Event handlers (learn more)
Asynchronous code (e.g.
setTimeout
or
requestAnimationFrame
callbacks)
Server side rendering
Errors thrown in the error boundary itself (rather than its children)
A class component becomes an error boundary if it defines either (or both) of the lifecycle methods
static getDerivedStateFromError()
or
componentDidCatch()
. Use
static getDerivedStateFromError()
to render a fallback UI after an error has been thrown. Use
componentDidCatch()
to log error information.
staticgetDerivedStateFromError(error){// Update state so the next render will show the fallback UI.return{hasError:true};} componentDidCatch(error, errorInfo){// You can also log the error to an error reporting servicelogErrorToMyService(error, errorInfo);} render(){ if(this.state.hasError){// You can render any custom fallback UIreturn<h1>Something went wrong.</h1>;} returnthis.props.children; } }
Then you can use it as a regular component:
<ErrorBoundary> <MyWidget/> </ErrorBoundary>
Error boundaries work like a JavaScript
catch {}
block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once and use it throughout your application.
Note that
error boundaries only catch errors in the components below them in the tree
. An error boundary can’t catch an error within itself. If an error boundary fails trying to render the error message, the error will propagate to the closest error boundary above it. This, too, is similar to how the
catch {}
block works in JavaScript.
Live Demo
Check out this example of declaring and using an error boundary.
Where to Place Error Boundaries
The granularity of error boundaries is up to you. You may wrap top-level route components to display a “Something went wrong” message to the user, just like how server-side frameworks often handle crashes. You may also wrap individual widgets in an error boundary to protect them from crashing the rest of the application.
New Behavior for Uncaught Errors
This change has an important implication.
As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.
We debated this decision, but in our experience it is worse to leave corrupted UI in place than to completely remove it. For example, in a product like Messenger leaving the broken UI visible could lead to somebody sending a message to the wrong person. Similarly, it is worse for a payments app to display a wrong amount than to render nothing.
This change means that as you migrate to React 16, you will likely uncover existing crashes in your application that have been unnoticed before. Adding error boundaries lets you provide better user experience when something goes wrong.
For example, Facebook Messenger wraps content of the sidebar, the info panel, the conversation log, and the message input into separate error boundaries. If some component in one of these UI areas crashes, the rest of them remain interactive.
We also encourage you to use JS error reporting services (or build your own) so that you can learn about unhandled exceptions as they happen in production, and fix them.
Component Stack Traces
React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces. Now you can see where exactly in the component tree the failure has happened:
You can also see the filenames and line numbers in the component stack trace. This works by default in Create React App projects:
If you don’t use Create React App, you can add this plugin manually to your Babel configuration. Note that it’s intended only for development and
must be disabled in production
.
Note
Component names displayed in the stack traces depend on the
Function.name
property. If you support older browsers and devices which may not yet provide this natively (e.g. IE 11), consider including a
Function.name
polyfill in your bundled application, such as
function.name-polyfill
. Alternatively, you may explicitly set the
displayName
property on all your components.
How About try/catch?
try
/
catch
is great but it only works for imperative code:
try{ showButton(); }catch(error){ // ... }
However, React components are declarative and specify
what
should be rendered:
<Button/>
Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a
componentDidUpdate
method caused by a
setState
somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
How About Event Handlers?
Error boundaries
do not
catch errors inside event handlers.
React doesn’t need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don’t happen during rendering. So if they throw, React still knows what to display on the screen.
If you need to catch an error inside an event handler, use the regular JavaScript
try
/
catch
statement:
handleClick(){ try{// Do something that could throw}catch(error){this.setState({ error });}}
render(){ if(this.state.error){return<h1>Caught an error.</h1>}return<buttononClick={this.handleClick}>Click Me</button>} }
Note that the above example is demonstrating regular JavaScript behavior and doesn’t use error boundaries.
Naming Changes from React 15
React 15 included a very limited support for error boundaries under a different method name:
unstable_handleError
. This method no longer works, and you will need to change it to
componentDidCatch
in your code starting from the first 16 beta release.
For this change, we’ve provided a codemod to automatically migrate your code.
React components hide their implementation details, including their rendered output. Other components using
FancyButton
usually will not need to
obtain a ref to the inner
button
DOM element. This is good because it prevents components from relying on each other’s DOM structure too much.
Although such encapsulation is desirable for application-level components like
FeedStory
or
Comment
, it can be inconvenient for highly reusable “leaf” components like
FancyButton
or
MyTextInput
. These components tend to be used throughout the application in a similar manner as a regular DOM
button
and
input
, and accessing their DOM nodes may be unavoidable for managing focus, selection, or animations.
Ref forwarding is an opt-in feature that lets some components take a
ref
they receive, and pass it further down (in other words, “forward” it) to a child.
In the example below,
FancyButton
uses
React.forwardRef
to obtain the
ref
passed to it, and then forward it to the DOM
button
that it renders:
// You can now get a ref directly to the DOM button: const ref = React.createRef(); <FancyButtonref={ref}>Click me!</FancyButton>;
This way, components using
FancyButton
can get a ref to the underlying
button
DOM node and access it if necessary—just like if they used a DOM
button
directly.
Here is a step-by-step explanation of what happens in the above example:
We create a React ref by calling
React.createRef
and assign it to a
ref
variable.
We pass our
ref
down to
<FancyButton ref={ref}>
by specifying it as a JSX attribute.
React passes the
ref
to the
(props, ref) => ...
function inside
forwardRef
as a second argument.
We forward this
ref
argument down to
<button ref={ref}>
by specifying it as a JSX attribute.
When the ref is attached,
ref.current
will point to the
<button>
DOM node.
Note
The second
ref
argument only exists when you define a component with
React.forwardRef
call. Regular function or class components don’t receive the
ref
argument, and ref is not available in props either.
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
Note for component library maintainers
When you start using
forwardRef
in a component library, you should treat it as a breaking change and release a new major version of your library.
This is because your library likely has an observably different behavior (such as what refs get assigned to, and what types are exported), and this can break apps and other libraries that depend on the old behavior.
Conditionally applying
React.forwardRef
when it exists is also not recommended for the same reasons: it changes how your library behaves and can break your users’ apps when they upgrade React itself.
Forwarding refs in higher-order components
This technique can also be particularly useful with higher-order components (also known as HOCs). Let’s start with an example HOC that logs component props to the console:
The “logProps” HOC passes all
props
through to the component it wraps, so the rendered output will be the same. For example, we can use this HOC to log all props that get passed to our “fancy button” component:
// Rather than exporting FancyButton, we export LogProps. // It will render a FancyButton though. exportdefaultlogProps(FancyButton);
There is one caveat to the above example: refs will not get passed through. That’s because
ref
is not a prop. Like
key
, it’s handled differently by React. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.
This means that refs intended for our
FancyButton
component will actually be attached to the
LogProps
component:
import FancyButton from'./FancyButton';
const ref = React.createRef(); // The FancyButton component we imported is the LogProps HOC. // Even though the rendered output will be the same, // Our ref will point to LogProps instead of the inner FancyButton component! // This means we can't call e.g. ref.current.focus() <FancyButton label="Click Me" handleClick={handleClick} ref={ref}/>;
Fortunately, we can explicitly forward refs to the inner
FancyButton
component using the
React.forwardRef
API.
React.forwardRef
accepts a render function that receives
props
and
ref
parameters and returns a React node. For example:
render(){ const{forwardedRef,...rest}=this.props; // Assign the custom prop "forwardedRef" as a ref return<Componentref={forwardedRef}{...rest}/>;} }
// Note the second param "ref" provided by React.forwardRef. // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef" // And it can then be attached to the Component. return React.forwardRef((props, ref)=>{return<LogProps{...props}forwardedRef={ref}/>;});}
Displaying a custom name in DevTools
React.forwardRef
accepts a render function. React DevTools uses this function to determine what to display for the ref forwarding component.
For example, the following component will appear as ”
ForwardRef
” in the DevTools:
// Give this component a more helpful display name in DevTools. // e.g. "ForwardRef(logProps(MyComponent))" const name = Component.displayName || Component.name; forwardRef.displayName =`logProps(${name})`; return React.forwardRef(forwardRef); }
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
<Columns />
would need to return multiple
<td>
elements in order for the rendered HTML to be valid. If a parent div was used inside the
render()
of
<Columns />
, then the resulting HTML will be invalid.
You can use
<></>
the same way you’d use any other element except that it doesn’t support keys or attributes.
Keyed Fragments
Fragments declared with the explicit
<React.Fragment>
syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:
functionGlossary(props){ return( <dl> {props.items.map(item=>( // Without the `key`, React will fire a key warning <React.Fragmentkey={item.id}> <dt>{item.term}</dt> <dd>{item.description}</dd> </React.Fragment> ))} </dl> ); }
key
is the only attribute that can be passed to
Fragment
. In the future, we may add support for additional attributes, such as event handlers.
Live Demo
You can try out the new JSX fragment syntax with this CodePen.
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.
Concretely,
a higher-order component is a function that takes a component and returns a new component.
In this document, we’ll discuss why higher-order components are useful, and how to write your own.
Use HOCs For Cross-Cutting Concerns
Note
We previously recommended mixins as a way to handle cross-cutting concerns. We’ve since realized that mixins create more trouble than they are worth. Read more about why we’ve moved away from mixins and how you can transition your existing components.
Components are the primary unit of code reuse in React. However, you’ll find that some patterns aren’t a straightforward fit for traditional components.
For example, say you have a
CommentList
component that subscribes to an external data source to render a list of comments:
classCommentListextendsReact.Component{ constructor(props){ super(props); this.handleChange =this.handleChange.bind(this); this.state ={ // "DataSource" is some global data source comments: DataSource.getComments() }; }
componentDidMount(){ // Subscribe to changes DataSource.addChangeListener(this.handleChange); }
componentWillUnmount(){ // Clean up listener DataSource.removeChangeListener(this.handleChange); }
handleChange(){ // Update component state whenever the data source changes this.setState({ comments: DataSource.getComments() }); }
CommentList
and
BlogPost
aren’t identical — they call different methods on
DataSource
, and they render different output. But much of their implementation is the same:
On mount, add a change listener to
DataSource
.
Inside the listener, call
setState
whenever the data source changes.
On unmount, remove the change listener.
You can imagine that in a large app, this same pattern of subscribing to
DataSource
and calling
setState
will occur over and over again. We want an abstraction that allows us to define this logic in a single place and share it across many components. This is where higher-order components excel.
We can write a function that creates components, like
CommentList
and
BlogPost
, that subscribe to
DataSource
. The function will accept as one of its arguments a child component that receives the subscribed data as a prop. Let’s call the function
withSubscription
:
The first parameter is the wrapped component. The second parameter retrieves the data we’re interested in, given a
DataSource
and the current props.
When
CommentListWithSubscription
and
BlogPostWithSubscription
are rendered,
CommentList
and
BlogPost
will be passed a
data
prop with the most current data retrieved from
DataSource
:
// This function takes a component... functionwithSubscription(WrappedComponent, selectData){ // ...and returns another component... returnclassextends React.Component { constructor(props){ super(props); this.handleChange =this.handleChange.bind(this); this.state ={ data:selectData(DataSource, props) }; }
componentDidMount(){ // ... that takes care of the subscription... DataSource.addChangeListener(this.handleChange); }
render(){ // ... and renders the wrapped component with the fresh data! // Notice that we pass through any additional props return<WrappedComponentdata={this.state.data}{...this.props}/>; } }; }
Note that a HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC
composes
the original component by
wrapping
it in a container component. A HOC is a pure function with zero side-effects.
And that’s it! The wrapped component receives all the props of the container, along with a new prop,
data
, which it uses to render its output. The HOC isn’t concerned with how or why the data is used, and the wrapped component isn’t concerned with where the data came from.
Because
withSubscription
is a normal function, you can add as many or as few arguments as you like. For example, you may want to make the name of the
data
prop configurable, to further isolate the HOC from the wrapped component. Or you could accept an argument that configures
shouldComponentUpdate
, or one that configures the data source. These are all possible because the HOC has full control over how the component is defined.
Like components, the contract between
withSubscription
and the wrapped component is entirely props-based. This makes it easy to swap one HOC for a different one, as long as they provide the same props to the wrapped component. This may be useful if you change data-fetching libraries, for example.
Don’t Mutate the Original Component. Use Composition.
Resist the temptation to modify a component’s prototype (or otherwise mutate it) inside a HOC.
functionlogProps(InputComponent){ InputComponent.prototype.componentDidUpdate=function(prevProps){ console.log('Current props: ',this.props); console.log('Previous props: ', prevProps); }; // The fact that we're returning the original input is a hint that it has // been mutated. return InputComponent; }
// EnhancedComponent will log whenever props are received const EnhancedComponent =logProps(InputComponent);
There are a few problems with this. One is that the input component cannot be reused separately from the enhanced component. More crucially, if you apply another HOC to
EnhancedComponent
that
also
mutates
componentDidUpdate
, the first HOC’s functionality will be overridden! This HOC also won’t work with function components, which do not have lifecycle methods.
Mutating HOCs are a leaky abstraction—the consumer must know how they are implemented in order to avoid conflicts with other HOCs.
Instead of mutation, HOCs should use composition, by wrapping the input component in a container component:
functionlogProps(WrappedComponent){ returnclassextends React.Component { componentDidUpdate(prevProps){ console.log('Current props: ',this.props); console.log('Previous props: ', prevProps); } render(){ // Wraps the input component in a container, without mutating it. Good! return<WrappedComponent{...this.props}/>; } } }
This HOC has the same functionality as the mutating version while avoiding the potential for clashes. It works equally well with class and function components. And because it’s a pure function, it’s composable with other HOCs, or even with itself.
You may have noticed similarities between HOCs and a pattern called
container components
. Container components are part of a strategy of separating responsibility between high-level and low-level concerns. Containers manage things like subscriptions and state, and pass props to components that handle things like rendering UI. HOCs use containers as part of their implementation. You can think of HOCs as parameterized container component definitions.
Convention: Pass Unrelated Props Through to the Wrapped Component
HOCs add features to a component. They shouldn’t drastically alter its contract. It’s expected that the component returned from a HOC has a similar interface to the wrapped component.
HOCs should pass through props that are unrelated to its specific concern. Most HOCs contain a render method that looks something like this:
render(){ // Filter out extra props that are specific to this HOC and shouldn't be // passed through const{ extraProp,...passThroughProps }=this.props;
// Inject props into the wrapped component. These are usually state values or // instance methods. const injectedProp = someStateOrInstanceMethod;
What?!
If you break it apart, it’s easier to see what’s going on.
// connect is a function that returns another function const enhance =connect(commentListSelector, commentListActions); // The returned function is a HOC, which returns a component that is connected // to the Redux store const ConnectedComment =enhance(CommentList);
In other words,
connect
is a higher-order function that returns a higher-order component!
This form may seem confusing or unnecessary, but it has a useful property. Single-argument HOCs like the one returned by the
connect
function have the signature
Component => Component
. Functions whose output type is the same as its input type are really easy to compose together.
// Instead of doing this... const EnhancedComponent =withRouter(connect(commentSelector)(WrappedComponent))
// ... you can use a function composition utility // compose(f, g, h) is the same as (...args) => f(g(h(...args))) const enhance =compose( // These are both single-argument HOCs withRouter, connect(commentSelector) ) const EnhancedComponent =enhance(WrappedComponent)
(This same property also allows
connect
and other enhancer-style HOCs to be used as decorators, an experimental JavaScript proposal.)
The
compose
utility function is provided by many third-party libraries including lodash (as
lodash.flowRight
), Redux, and Ramda.
Convention: Wrap the Display Name for Easy Debugging
The container components created by HOCs show up in the React Developer Tools like any other component. To ease debugging, choose a display name that communicates that it’s the result of a HOC.
The most common technique is to wrap the display name of the wrapped component. So if your higher-order component is named
withSubscription
, and the wrapped component’s display name is
CommentList
, use the display name
WithSubscription(CommentList)
:
Higher-order components come with a few caveats that aren’t immediately obvious if you’re new to React.
Don’t Use HOCs Inside the render Method
React’s diffing algorithm (called Reconciliation) uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from
render
is identical (
===
) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they’re not equal, the previous subtree is unmounted completely.
Normally, you shouldn’t need to think about this. But it matters for HOCs because it means you can’t apply a HOC to a component within the render method of a component:
render(){ // A new version of EnhancedComponent is created on every render // EnhancedComponent1 !== EnhancedComponent2 const EnhancedComponent =enhance(MyComponent); // That causes the entire subtree to unmount/remount each time! return<EnhancedComponent/>; }
The problem here isn’t just about performance — remounting a component causes the state of that component and all of its children to be lost.
Instead, apply HOCs outside the component definition so that the resulting component is created only once. Then, its identity will be consistent across renders. This is usually what you want, anyway.
In those rare cases where you need to apply a HOC dynamically, you can also do it inside a component’s lifecycle methods or its constructor.
Static Methods Must Be Copied Over
Sometimes it’s useful to define a static method on a React component. For example, Relay containers expose a static method
getFragment
to facilitate the composition of GraphQL fragments.
When you apply a HOC to a component, though, the original component is wrapped with a container component. That means the new component does not have any of the static methods of the original component.
// Define a static method WrappedComponent.staticMethod=function(){/*...*/} // Now apply a HOC const EnhancedComponent =enhance(WrappedComponent);
// The enhanced component has no static method typeof EnhancedComponent.staticMethod ==='undefined'// true
To solve this, you could copy the methods onto the container before returning it:
functionenhance(WrappedComponent){ classEnhanceextendsReact.Component{/*...*/} // Must know exactly which method(s) to copy :( Enhance.staticMethod = WrappedComponent.staticMethod; return Enhance; }
However, this requires you to know exactly which methods need to be copied. You can use hoist-non-react-statics to automatically copy all non-React static methods:
// ...export the method separately... export{ someFunction };
// ...and in the consuming module, import both import MyComponent,{ someFunction }from'./MyComponent.js';
Refs Aren’t Passed Through
While the convention for higher-order components is to pass through all props to the wrapped component, this does not work for refs. That’s because
ref
is not really a prop — like
key
, it’s handled specially by React. If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component.
The solution for this problem is to use the
React.forwardRef
API (introduced with React 16.3). Learn more about it in the forwarding refs section.