url
stringlengths 17
87
| content
stringlengths 152
81.8k
|
---|---|
https://react.dev | ![logo by @sawaratsuki1004](/_next/image?url=%2Fimages%2Fuwu.png&w=640&q=75 "logo by @sawaratsuki1004")
# React
The library for web and native user interfaces
[Learn React](https://react.dev/learn)[API Reference](https://react.dev/reference/react)
## Create user interfaces from components
React lets you build user interfaces out of individual pieces called components. Create your own React components like `Thumbnail`, `LikeButton`, and `Video`. Then combine them into entire screens, pages, and apps.
### Video.js
```
function Video({ video }) {
return (
<div>
<Thumbnail video={video} />
<a href={video.url}>
<h3>{video.title}</h3>
<p>{video.description}</p>
</a>
<LikeButton video={video} />
</div>
);
}
```
[]()[**My video**
\
Video description]()
Whether you work on your own or with thousands of other developers, using React feels the same. It is designed to let you seamlessly combine components written by independent people, teams, and organizations.
## Write components with code and markup
React components are JavaScript functions. Want to show some content conditionally? Use an `if` statement. Displaying a list? Try array `map()`. Learning React is learning programming.
### VideoList.js
```
function VideoList({ videos, emptyHeading }) {
const count = videos.length;
let heading = emptyHeading;
if (count > 0) {
const noun = count > 1 ? 'Videos' : 'Video';
heading = count + ' ' + noun;
}
return (
<section>
<h2>{heading}</h2>
{videos.map(video =>
<Video key={video.id} video={video} />
)}
</section>
);
}
```
## 3 Videos
[]()[**First video**
\
Video description]()
[]()[**Second video**
\
Video description]()
[]()[**Third video**
\
Video description]()
This markup syntax is called JSX. It is a JavaScript syntax extension popularized by React. Putting JSX markup close to related rendering logic makes React components easy to create, maintain, and delete.
## Add interactivity wherever you need it
React components receive data and return what should appear on the screen. You can pass them new data in response to an interaction, like when the user types into an input. React will then update the screen to match the new data.
### SearchableVideoList.js
```
import { useState } from 'react';
function SearchableVideoList({ videos }) {
const [searchText, setSearchText] = useState('');
const foundVideos = filterVideos(videos, searchText);
return (
<>
<SearchInput
value={searchText}
onChange={newText => setSearchText(newText)} />
<VideoList
videos={foundVideos}
emptyHeading={`No matches for “${searchText}”`} />
</>
);
}
```
example.com/videos.html
# React Videos
A brief history of React
Search
## 5 Videos
[](https://www.youtube.com/watch?v=8pDqJVdNa44)[**React: The Documentary**
\
The origin story of React](https://www.youtube.com/watch?v=8pDqJVdNa44)
[](https://www.youtube.com/watch?v=x7cQ3mrcKaY)[**Rethinking Best Practices**
\
Pete Hunt (2013)](https://www.youtube.com/watch?v=x7cQ3mrcKaY)
[](https://www.youtube.com/watch?v=KVZ-P-ZI6W4)[**Introducing React Native**
\
Tom Occhino (2015)](https://www.youtube.com/watch?v=KVZ-P-ZI6W4)
[](https://www.youtube.com/watch?v=V-QO-KO90iQ)[**Introducing React Hooks**
\
Sophie Alpert and Dan Abramov (2018)](https://www.youtube.com/watch?v=V-QO-KO90iQ)
[](https://www.youtube.com/watch?v=TQQPAU21ZUw)[**Introducing Server Components**
\
Dan Abramov and Lauren Tan (2020)](https://www.youtube.com/watch?v=TQQPAU21ZUw)
You don’t have to build your whole page in React. Add React to your existing HTML page, and render interactive React components anywhere on it.
[Add React to your page](https://react.dev/learn/add-react-to-an-existing-project)
## Go full-stack with a framework
React is a library. It lets you put components together, but it doesn’t prescribe how to do routing and data fetching. To build an entire app with React, we recommend a full-stack React framework like [Next.js](https://nextjs.org) or [Remix](https://remix.run).
### confs/\[slug].js
```
import { db } from './database.js';
import { Suspense } from 'react';
async function ConferencePage({ slug }) {
const conf = await db.Confs.find({ slug });
return (
<ConferenceLayout conf={conf}>
<Suspense fallback={<TalksLoading />}>
<Talks confId={conf.id} />
</Suspense>
</ConferenceLayout>
);
}
async function Talks({ confId }) {
const talks = await db.Talks.findAll({ confId });
const videos = talks.map(talk => talk.video);
return <SearchableVideoList videos={videos} />;
}
```
example.com/confs/react-conf-2021
React Conf 2021React Conf 2019
![](/images/home/conf2021/cover.svg)
Search
## 19 Videos
[![](/images/home/conf2021/andrew.jpg)![](/images/home/conf2021/lauren.jpg)![](/images/home/conf2021/juan.jpg)![](/images/home/conf2021/rick.jpg)
\
React Conf](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=1)
[**React 18 Keynote**
\
The React Team](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=1)
[![](/images/home/conf2021/shruti.jpg)
\
React Conf](https://www.youtube.com/watch?v=ytudH8je5ko&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=2)
[**React 18 for App Developers**
\
Shruti Kapoor](https://www.youtube.com/watch?v=ytudH8je5ko&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=2)
[![](/images/home/conf2021/shaundai.jpg)
\
React Conf](https://www.youtube.com/watch?v=pj5N-Khihgc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=3)
[**Streaming Server Rendering with Suspense**
\
Shaundai Person](https://www.youtube.com/watch?v=pj5N-Khihgc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=3)
[![](/images/home/conf2021/aakansha.jpg)
\
React Conf](https://www.youtube.com/watch?v=qn7gRClrC9U&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=4)
[**The First React Working Group**
\
Aakansha Doshi](https://www.youtube.com/watch?v=qn7gRClrC9U&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=4)
[![](/images/home/conf2021/brian.jpg)
\
React Conf](https://www.youtube.com/watch?v=oxDfrke8rZg&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=5)
[**React Developer Tooling**
\
Brian Vaughn](https://www.youtube.com/watch?v=oxDfrke8rZg&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=5)
[![](/images/home/conf2021/xuan.jpg)
\
React Conf](https://www.youtube.com/watch?v=lGEMwh32soc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=6)
[**React without memo**
\
Xuan Huang (黄玄)](https://www.youtube.com/watch?v=lGEMwh32soc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=6)
[![](/images/home/conf2021/rachel.jpg)
\
React Conf](https://www.youtube.com/watch?v=mneDaMYOKP8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=7)
[**React Docs Keynote**
\
Rachel Nabors](https://www.youtube.com/watch?v=mneDaMYOKP8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=7)
[![](/images/home/conf2021/debbie.jpg)
\
React Conf](https://www.youtube.com/watch?v=-7odLW_hG7s&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=8)
[**Things I Learnt from the New React Docs**
\
Debbie O'Brien](https://www.youtube.com/watch?v=-7odLW_hG7s&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=8)
[![](/images/home/conf2021/sarah.jpg)
\
React Conf](https://www.youtube.com/watch?v=5X-WEQflCL0&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=9)
[**Learning in the Browser**
\
Sarah Rainsberger](https://www.youtube.com/watch?v=5X-WEQflCL0&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=9)
[![](/images/home/conf2021/linton.jpg)
\
React Conf](https://www.youtube.com/watch?v=7cPWmID5XAk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=10)
[**The ROI of Designing with React**
\
Linton Ye](https://www.youtube.com/watch?v=7cPWmID5XAk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=10)
[![](/images/home/conf2021/delba.jpg)
\
React Conf](https://www.youtube.com/watch?v=zL8cz2W0z34&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=11)
[**Interactive Playgrounds with React**
\
Delba de Oliveira](https://www.youtube.com/watch?v=zL8cz2W0z34&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=11)
[![](/images/home/conf2021/robert.jpg)
\
React Conf](https://www.youtube.com/watch?v=lhVGdErZuN4&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=12)
[**Re-introducing Relay**
\
Robert Balicki](https://www.youtube.com/watch?v=lhVGdErZuN4&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=12)
[![](/images/home/conf2021/eric.jpg)![](/images/home/conf2021/steven.jpg)
\
React Conf](https://www.youtube.com/watch?v=9L4FFrvwJwY&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=13)
[**React Native Desktop**
\
Eric Rozell and Steven Moyes](https://www.youtube.com/watch?v=9L4FFrvwJwY&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=13)
[![](/images/home/conf2021/roman.jpg)
\
React Conf](https://www.youtube.com/watch?v=NLj73vrc2I8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=14)
[**On-device Machine Learning for React Native**
\
Roman Rädle](https://www.youtube.com/watch?v=NLj73vrc2I8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=14)
[![](/images/home/conf2021/daishi.jpg)
\
React Conf](https://www.youtube.com/watch?v=oPfSC5bQPR8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=15)
[**React 18 for External Store Libraries**
\
Daishi Kato](https://www.youtube.com/watch?v=oPfSC5bQPR8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=15)
[![](/images/home/conf2021/diego.jpg)
\
React Conf](https://www.youtube.com/watch?v=dcm8fjBfro8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=16)
[**Building Accessible Components with React 18**
\
Diego Haz](https://www.youtube.com/watch?v=dcm8fjBfro8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=16)
[![](/images/home/conf2021/tafu.jpg)
\
React Conf](https://www.youtube.com/watch?v=S4a0QlsH0pU&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=17)
[**Accessible Japanese Form Components with React**
\
Tafu Nakazaki](https://www.youtube.com/watch?v=S4a0QlsH0pU&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=17)
[![](/images/home/conf2021/lyle.jpg)
\
React Conf](https://www.youtube.com/watch?v=b3l4WxipFsE&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=18)
[**UI Tools for Artists**
\
Lyle Troxell](https://www.youtube.com/watch?v=b3l4WxipFsE&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=18)
[![](/images/home/conf2021/helen.jpg)
\
React Conf](https://www.youtube.com/watch?v=HS6vIYkSNks&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=19)
[**Hydrogen + React 18**
\
Helen Lin](https://www.youtube.com/watch?v=HS6vIYkSNks&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=19)
React is also an architecture. Frameworks that implement it let you fetch data in asynchronous components that run on the server or even during the build. Read data from a file or a database, and pass it down to your interactive components.
[Get started with a framework](https://react.dev/learn/start-a-new-react-project)
## Use the best from every platform
People love web and native apps for different reasons. React lets you build both web apps and native apps using the same skills. It leans upon each platform’s unique strengths to let your interfaces feel just right on every platform.
example.com
#### Stay true to the web
People expect web app pages to load fast. On the server, React lets you start streaming HTML while you’re still fetching data, progressively filling in the remaining content before any JavaScript code loads. On the client, React can use standard web APIs to keep your UI responsive even in the middle of rendering.
12:23 PM
#### Go truly native
People expect native apps to look and feel like their platform. [React Native](https://reactnative.dev) and [Expo](https://github.com/expo/expo) let you build apps in React for Android, iOS, and more. They look and feel native because their UIs *are* truly native. It’s not a web view—your React components render real Android and iOS views provided by the platform.
With React, you can be a web *and* a native developer. Your team can ship to many platforms without sacrificing the user experience. Your organization can bridge the platform silos, and form teams that own entire features end-to-end.
[Build for native platforms](https://reactnative.dev/)
## Upgrade when the future is ready
React approaches changes with care. Every React commit is tested on business-critical surfaces with over a billion users. Over 100,000 React components at Meta help validate every migration strategy.
The React team is always researching how to improve React. Some research takes years to pay off. React has a high bar for taking a research idea into production. Only proven approaches become a part of React.
[Read more React news](https://react.dev/blog)
Latest React News
[**React 19**
\
December 05, 2024](https://react.dev/blog/2024/12/05/react-19)
[**React Compiler Beta Release and Roadmap**
\
October 21, 2024](https://react.dev/blog/2024/10/21/react-compiler-beta-release)
[**React Conf 2024 Recap**
\
May 22, 2024](https://react.dev/blog/2024/05/22/react-conf-2024-recap)
[**React 19 RC**
\
April 25, 2024](https://react.dev/blog/2024/04/25/react-19)
[Read more React news](https://react.dev/blog)
## Join a community of millions
You’re not alone. Two million developers from all over the world visit the React docs every month. React is something that people and teams can agree on.
![People singing karaoke at React Conf](/images/home/community/react_conf_fun.webp)
![Sunil Pai speaking at React India](/images/home/community/react_india_sunil.webp)
![A hallway conversation between two people at React Conf](/images/home/community/react_conf_hallway.webp)
![A hallway conversation at React India](/images/home/community/react_india_hallway.webp)
![Elizabet Oliveira speaking at React Conf](/images/home/community/react_conf_elizabet.webp)
![People taking a group selfie at React India](/images/home/community/react_india_selfie.webp)
![Nat Alison speaking at React Conf](/images/home/community/react_conf_nat.webp)
![Organizers greeting attendees at React India](/images/home/community/react_india_team.webp)
![People singing karaoke at React Conf](/images/home/community/react_conf_fun.webp)
![Sunil Pai speaking at React India](/images/home/community/react_india_sunil.webp)
![A hallway conversation between two people at React Conf](/images/home/community/react_conf_hallway.webp)
![A hallway conversation at React India](/images/home/community/react_india_hallway.webp)
![Elizabet Oliveira speaking at React Conf](/images/home/community/react_conf_elizabet.webp)
![People taking a group selfie at React India](/images/home/community/react_india_selfie.webp)
![Nat Alison speaking at React Conf](/images/home/community/react_conf_nat.webp)
![Organizers greeting attendees at React India](/images/home/community/react_india_team.webp)
This is why React is more than a library, an architecture, or even an ecosystem. React is a community. It’s a place where you can ask for help, find opportunities, and meet new friends. You will meet both developers and designers, beginners and experts, researchers and artists, teachers and students. Our backgrounds may be very different, but React lets us all create user interfaces together.
![logo by @sawaratsuki1004](/images/uwu.png "logo by @sawaratsuki1004")
## Welcome to the React community
[Get Started](https://react.dev/learn) |
https://react.dev/community | [Community](https://react.dev/community)
# React Community[Link for this heading]()
React has a community of millions of developers. On this page we’ve listed some React-related communities that you can be a part of; see the other pages in this section for additional online and in-person learning materials.
## Code of Conduct[Link for Code of Conduct]()
Before participating in React’s communities, [please read our Code of Conduct.](https://github.com/facebook/react/blob/main/CODE_OF_CONDUCT.md) We have adopted the [Contributor Covenant](https://www.contributor-covenant.org/) and we expect that all community members adhere to the guidelines within.
## Stack Overflow[Link for Stack Overflow]()
Stack Overflow is a popular forum to ask code-level questions or if you’re stuck with a specific error. Read through the [existing questions](https://stackoverflow.com/questions/tagged/reactjs) tagged with **reactjs** or [ask your own](https://stackoverflow.com/questions/ask?tags=reactjs)!
## Popular Discussion Forums[Link for Popular Discussion Forums]()
There are many online forums which are a great place for discussion about best practices and application architecture as well as the future of React. If you have an answerable code-level question, Stack Overflow is usually a better fit.
Each community consists of many thousands of React users.
- [DEV’s React community](https://dev.to/t/react)
- [Hashnode’s React community](https://hashnode.com/n/reactjs)
- [Reactiflux online chat](https://discord.gg/reactiflux)
- [Reddit’s React community](https://www.reddit.com/r/reactjs/)
## News[Link for News]()
For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs) and the [official React blog](https://react.dev/blog) on this website.
[NextReact Conferences](https://react.dev/community/conferences) |
https://react.dev/reference/react | [API Reference](https://react.dev/reference/react)
# React Reference Overview[Link for this heading]()
This section provides detailed reference documentation for working with React. For an introduction to React, please visit the [Learn](https://react.dev/learn) section.
The React reference documentation is broken down into functional subsections:
## React[Link for React]()
Programmatic React features:
- [Hooks](https://react.dev/reference/react/hooks) - Use different React features from your components.
- [Components](https://react.dev/reference/react/components) - Built-in components that you can use in your JSX.
- [APIs](https://react.dev/reference/react/apis) - APIs that are useful for defining components.
- [Directives](https://react.dev/reference/rsc/directives) - Provide instructions to bundlers compatible with React Server Components.
## React DOM[Link for React DOM]()
React-dom contains features that are only supported for web applications (which run in the browser DOM environment). This section is broken into the following:
- [Hooks](https://react.dev/reference/react-dom/hooks) - Hooks for web applications which run in the browser DOM environment.
- [Components](https://react.dev/reference/react-dom/components) - React supports all of the browser built-in HTML and SVG components.
- [APIs](https://react.dev/reference/react-dom) - The `react-dom` package contains methods supported only in web applications.
- [Client APIs](https://react.dev/reference/react-dom/client) - The `react-dom/client` APIs let you render React components on the client (in the browser).
- [Server APIs](https://react.dev/reference/react-dom/server) - The `react-dom/server` APIs let you render React components to HTML on the server.
## Rules of React[Link for Rules of React]()
React has idioms — or rules — for how to express patterns in a way that is easy to understand and yields high-quality applications:
- [Components and Hooks must be pure](https://react.dev/reference/rules/components-and-hooks-must-be-pure) – Purity makes your code easier to understand, debug, and allows React to automatically optimize your components and hooks correctly.
- [React calls Components and Hooks](https://react.dev/reference/rules/react-calls-components-and-hooks) – React is responsible for rendering components and hooks when necessary to optimize the user experience.
- [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks) – Hooks are defined using JavaScript functions, but they represent a special type of reusable UI logic with restrictions on where they can be called.
## Legacy APIs[Link for Legacy APIs]()
- [Legacy APIs](https://react.dev/reference/react/legacy) - Exported from the `react` package, but not recommended for use in newly written code.
[NextHooks](https://react.dev/reference/react/hooks) |
https://react.dev/blog | [Blog](https://react.dev/blog)
# React Blog[Link for this heading]()
This blog is the official source for the updates from the React team. Anything important, including release notes or deprecation notices, will be posted here first. You can also follow the [@reactjs](https://twitter.com/reactjs) account on Twitter, but you won’t miss anything essential if you only read this blog.
[**React v19**
\
December 5, 2024
\
In the React 19 Upgrade Guide, we shared step-by-step instructions for upgrading your app to React 19. In this post, we’ll give an overview of the new features in React 19, and how you can adopt them …
\
Read more](https://react.dev/blog/2024/12/05/react-19)
[**React Compiler Beta Release**
\
October 21, 2024
\
We announced an experimental release of React Compiler at React Conf 2024. We’ve made a lot of progress since then, and in this post we want to share what’s next for React Compiler …
\
Read more](https://react.dev/blog/2024/10/21/react-compiler-beta-release)
[**React Conf 2024 Recap**
\
May 22, 2024
\
Last week we hosted React Conf 2024, a two-day conference in Henderson, Nevada where 700+ attendees gathered in-person to discuss the latest in UI engineering. This was our first in-person conference since 2019, and we were thrilled to be able to bring the community together again …
\
Read more](https://react.dev/blog/2024/05/22/react-conf-2024-recap)
[**React 19 Upgrade Guide**
\
April 25, 2024
\
The improvements added to React 19 require some breaking changes, but we’ve worked to make the upgrade as smooth as possible, and we don’t expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading libraries to React 19 …
\
Read more](https://react.dev/blog/2024/04/25/react-19-upgrade-guide)
[**React Labs: What We've Been Working On – February 2024**
\
February 15, 2024
\
In React Labs posts, we write about projects in active research and development. Since our last update, we’ve made significant progress on React Compiler, new features, and React 19, and we’d like to share what we learned.
\
Read more](https://react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024)
[**React Canaries: Incremental Feature Rollout Outside Meta**
\
May 3, 2023
\
Traditionally, new React features used to only be available at Meta first, and land in the open source releases later. We’d like to offer the React community an option to adopt individual new features as soon as their design is close to final—similar to how Meta uses React internally. We are introducing a new officially supported Canary release channel. It lets curated setups like frameworks decouple adoption of individual React features from the React release schedule.
\
Read more](https://react.dev/blog/2023/05/03/react-canaries)
[**React Labs: What We've Been Working On – March 2023**
\
March 22, 2023
\
In React Labs posts, we write about projects in active research and development. Since our last update, we’ve made significant progress on React Server Components, Asset Loading, Optimizing Compiler, Offscreen Rendering, and Transition Tracing, and we’d like to share what we learned.
\
Read more](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023)
[**Introducing react.dev**
\
March 16, 2023
\
Today we are thrilled to launch react.dev, the new home for React and its documentation. In this post, we would like to give you a tour of the new site.
\
Read more](https://react.dev/blog/2023/03/16/introducing-react-dev)
[**React Labs: What We've Been Working On – June 2022**
\
June 15, 2022
\
React 18 was years in the making, and with it brought valuable lessons for the React team. Its release was the result of many years of research and exploring many paths. Some of those paths were successful; many more were dead-ends that led to new insights. One lesson we’ve learned is that it’s frustrating for the community to wait for new features without having insight into these paths that we’re exploring…
\
Read more](https://react.dev/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022)
[**React v18.0**
\
March 29, 2022
\
React 18 is now available on npm! In our last post, we shared step-by-step instructions for upgrading your app to React 18. In this post, we’ll give an overview of what’s new in React 18, and what it means for the future…
\
Read more](https://react.dev/blog/2022/03/29/react-v18)
[**How to Upgrade to React 18**
\
March 8, 2022
\
As we shared in the release post, React 18 introduces features powered by our new concurrent renderer, with a gradual adoption strategy for existing applications. In this post, we will guide you through the steps for upgrading to React 18…
\
Read more](https://react.dev/blog/2022/03/08/react-18-upgrade-guide)
[**React Conf 2021 Recap**
\
December 17, 2021
\
Last week we hosted our 6th React Conf. In previous years, we’ve used the React Conf stage to deliver industry changing announcements such as React Native and React Hooks. This year, we shared our multi-platform vision for React, starting with the release of React 18 and gradual adoption of concurrent features…
\
Read more](https://react.dev/blog/2021/12/17/react-conf-2021-recap)
[**The Plan for React 18**
\
June 8, 2021
\
The React team is excited to share a few updates:
\
We’ve started work on the React 18 release, which will be our next major version. We’ve created a Working Group to prepare the community for gradual adoption of new features in React 18. We’ve published a React 18 Alpha so that library authors can try it and provide feedback…
\
Read more](https://react.dev/blog/2021/06/08/the-plan-for-react-18)
[**Introducing Zero-Bundle-Size React Server Components**
\
December 21, 2020
\
2020 has been a long year. As it comes to an end we wanted to share a special Holiday Update on our research into zero-bundle-size React Server Components. To introduce React Server Components, we have prepared a talk and a demo. If you want, you can check them out during the holidays, or later when work picks back up in the new year…
\
Read more](https://react.dev/blog/2020/12/21/data-fetching-with-react-server-components)
* * *
### All release notes[Link for All release notes]()
Not every React release deserves its own blog post, but you can find a detailed changelog for every release in the [`CHANGELOG.md`](https://github.com/facebook/react/blob/main/CHANGELOG.md) file in the React repository, as well as on the [Releases](https://github.com/facebook/react/releases) page.
* * *
### Older posts[Link for Older posts]()
See the [older posts.](https://reactjs.org/blog/all.html) |
https://react.dev/versions | [React Docs](https://react.dev/)
# React Versions[Link for this heading]()
The React docs at [react.dev](https://react.dev) provide documentation for the latest version of React.
We aim to keep the docs updated within major versions, and do not publish versions for each minor or patch version. When a new major is released, we archive the docs for the previous version as `x.react.dev`. See our [versioning policy](https://react.dev/community/versioning-policy) for more info.
You can find an archive of previous major versions below.
## Latest version: 19.0[Link for Latest version: 19.0]()
- [react.dev](https://react.dev)
## Previous versions[Link for Previous versions]()
- [18.react.dev](https://18.react.dev)
- [17.react.dev](https://17.react.dev)
- [16.react.dev](https://16.react.dev)
- [15.react.dev](https://15.react.dev)
### Note
#### Legacy Docs[Link for Legacy Docs]()
In 2023, we [launched our new docs](https://react.dev/blog/2023/03/16/introducing-react-dev) for React 18 as [react.dev](https://react.dev). The legacy React 18 docs are available at [legacy.reactjs.org](https://legacy.reactjs.org). Versions 17 and below are hosted on legacy sites.
For versions older than React 15, see [15.react.dev](https://15.react.dev).
## Changelog[Link for Changelog]()
### React 19[Link for React 19]()
**Blog Posts**
- [React v19](https://react.dev/blog/2024/12/05/react-19)
- [React 19 Upgrade Guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide)
- [React Compiler Beta Release](https://react.dev/blog/2024/10/21/react-compiler-beta-release)
**Talks**
- [React 19 Keynote](https://www.youtube.com/watch?v=lyEKhv8-3n0)
- [A Roadmap to React 19](https://www.youtube.com/watch?v=R0B2HsSM78s)
- [What’s new in React 19](https://www.youtube.com/watch?v=AJOGzVygGcY)
- [React for Two Computers](https://www.youtube.com/watch?v=ozI4V_29fj4)
- [React Compiler Deep Dive](https://www.youtube.com/watch?v=uA_PVyZP7AI)
- [React Compiler Case Studies](https://www.youtube.com/watch?v=lvhPq5chokM)
- [React 19 Deep Dive: Coordinating HTML](https://www.youtube.com/watch?v=IBBN-s77YSI)
**Releases**
- [v19.0.0 (December, 2024)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 18[Link for React 18]()
**Blog Posts**
- [React v18.0](https://react.dev/blog/2022/03/29/react-v18)
- [How to Upgrade to React 18](https://react.dev/blog/2022/03/08/react-18-upgrade-guide)
- [The Plan for React 18](https://react.dev/blog/2021/06/08/the-plan-for-react-18)
**Talks**
- [React 18 Keynote](https://www.youtube.com/watch?v=FZ0cG47msEk)
- [React 18 for app developers](https://www.youtube.com/watch?v=ytudH8je5ko)
- [Streaming Server Rendering with Suspense](https://www.youtube.com/watch?v=pj5N-Khihgc)
- [React without memo](https://www.youtube.com/watch?v=lGEMwh32soc)
- [React Docs Keynote](https://www.youtube.com/watch?v=mneDaMYOKP8)
- [React Developer Tooling](https://www.youtube.com/watch?v=oxDfrke8rZg)
- [The first React Working Group](https://www.youtube.com/watch?v=qn7gRClrC9U)
- [React 18 for External Store Libraries](https://www.youtube.com/watch?v=oPfSC5bQPR8)
**Releases**
- [v18.3.1 (April, 2024)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v18.3.0 (April, 2024)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v18.2.0 (June, 2022)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v18.1.0 (April, 2022)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v18.0.0 (March 2022)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 17[Link for React 17]()
**Blog Posts**
- [React v17.0](https://legacy.reactjs.org/blog/2020/10/20/react-v17.html)
- [Introducing the New JSX Transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html)
- [React v17.0 Release Candidate: No New Features](https://legacy.reactjs.org/blog/2020/08/10/react-v17-rc.html)
**Releases**
- [v17.0.2 (March 2021)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v17.0.1 (October 2020)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v17.0.0 (October 2020)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 16[Link for React 16]()
**Blog Posts**
- [React v16.0](https://legacy.reactjs.org/blog/2017/09/26/react-v16.0.html)
- [DOM Attributes in React 16](https://legacy.reactjs.org/blog/2017/09/08/dom-attributes-in-react-16.html)
- [Error Handling in React 16](https://legacy.reactjs.org/blog/2017/07/26/error-handling-in-react-16.html)
- [React v16.2.0: Improved Support for Fragments](https://legacy.reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html)
- [React v16.4.0: Pointer Events](https://legacy.reactjs.org/blog/2018/05/23/react-v-16-4.html)
- [React v16.4.2: Server-side vulnerability fix](https://legacy.reactjs.org/blog/2018/08/01/react-v-16-4-2.html)
- [React v16.6.0: lazy, memo and contextType](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html)
- [React v16.7: No, This Is Not the One With Hooks](https://legacy.reactjs.org/blog/2018/12/19/react-v-16-7.html)
- [React v16.8: The One With Hooks](https://legacy.reactjs.org/blog/2019/02/06/react-v16.8.0.html)
- [React v16.9.0 and the Roadmap Update](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html)
- [React v16.13.0](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html)
**Releases**
- [v16.14.0 (October 2020)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.13.1 (March 2020)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.13.0 (February 2020)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.12.0 (November 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.11.0 (October 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.10.2 (October 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.10.1 (September 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.10.0 (September 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.9.0 (August 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.8.6 (March 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.8.5 (March 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.8.4 (March 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.8.3 (February 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.8.2 (February 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.8.1 (February 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.8.0 (February 2019)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.7.0 (December 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.6.3 (November 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.6.2 (November 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.6.1 (November 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.6.0 (October 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.5.2 (September 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.5.1 (September 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.5.0 (September 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.4.2 (August 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.4.1 (June 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.4.0 (May 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.3.3 (August 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.3.2 (April 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.3.1 (April 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.3.0 (March 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.2.1 (August 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.2.0 (November 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.1.2 (August 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.1.1 (November 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.1.0 (November 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.0.1 (August 2018)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v16.0 (September 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 15[Link for React 15]()
**Blog Posts**
- [React v15.0](https://legacy.reactjs.org/blog/2016/04/07/react-v15.html)
- [React v15.0 Release Candidate 2](https://legacy.reactjs.org/blog/2016/03/16/react-v15-rc2.html)
- [React v15.0 Release Candidate](https://legacy.reactjs.org/blog/2016/03/07/react-v15-rc1.html)
- [New Versioning Scheme](https://legacy.reactjs.org/blog/2016/02/19/new-versioning-scheme.html)
- [Discontinuing IE 8 Support in React DOM](https://legacy.reactjs.org/blog/2016/01/12/discontinuing-ie8-support.html)
- [Introducing React’s Error Code System](https://legacy.reactjs.org/blog/2016/07/11/introducing-reacts-error-code-system.html)
- [React v15.0.1](https://legacy.reactjs.org/blog/2016/04/08/react-v15.0.1.html)
- [React v15.4.0](https://legacy.reactjs.org/blog/2016/11/16/react-v15.4.0.html)
- [React v15.5.0](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html)
- [React v15.6.0](https://legacy.reactjs.org/blog/2017/06/13/react-v15.6.0.html)
- [React v15.6.2](https://legacy.reactjs.org/blog/2017/09/25/react-v15.6.2.html)
**Releases**
- [v15.7.0 (October 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.6.2 (September 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.6.1 (June 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.6.0 (June 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.5.4 (April 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.5.3 (April 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.5.2 (April 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.5.1 (April 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.5.0 (April 2017)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.4.2 (January 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.4.1 (November 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.4.0 (November 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.3.2 (September 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.3.1 (August 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.3.0 (July 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.2.1 (July 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.2.0 (July 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.1.0 (May 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.0.2 (April 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.0.1 (April 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v15.0.0 (April 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 0.14[Link for React 0.14]()
**Blog Posts**
- [React v0.14](https://legacy.reactjs.org/blog/2015/10/07/react-v0.14.html)
- [React v0.14 Release Candidate](https://legacy.reactjs.org/blog/2015/09/10/react-v0.14-rc1.html)
- [React v0.14 Beta 1](https://legacy.reactjs.org/blog/2015/07/03/react-v0.14-beta-1.html)
- [New React Developer Tools](https://legacy.reactjs.org/blog/2015/09/02/new-react-developer-tools.html)
- [New React Devtools Beta](https://legacy.reactjs.org/blog/2015/08/03/new-react-devtools-beta.html)
- [React v0.14.1](https://legacy.reactjs.org/blog/2015/10/28/react-v0.14.1.html)
- [React v0.14.2](https://legacy.reactjs.org/blog/2015/11/02/react-v0.14.2.html)
- [React v0.14.3](https://legacy.reactjs.org/blog/2015/11/18/react-v0.14.3.html)
- [React v0.14.4](https://legacy.reactjs.org/blog/2015/12/29/react-v0.14.4.html)
- [React v0.14.8](https://legacy.reactjs.org/blog/2016/03/29/react-v0.14.8.html)
**Releases**
- [v0.14.10 (October 2020)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.8 (March 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.7 (January 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.6 (January 2016)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.5 (December 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.4 (December 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.3 (November 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.2 (November 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.1 (October 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.14.0 (October 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 0.13[Link for React 0.13]()
**Blog Posts**
- [React Native v0.4](https://legacy.reactjs.org/blog/2015/04/17/react-native-v0.4.html)
- [React v0.13](https://legacy.reactjs.org/blog/2015/03/10/react-v0.13.html)
- [React v0.13 RC2](https://legacy.reactjs.org/blog/2015/03/03/react-v0.13-rc2.html)
- [React v0.13 RC](https://legacy.reactjs.org/blog/2015/02/24/react-v0.13-rc1.html)
- [React v0.13.0 Beta 1](https://legacy.reactjs.org/blog/2015/01/27/react-v0.13.0-beta-1.html)
- [Streamlining React Elements](https://legacy.reactjs.org/blog/2015/02/24/streamlining-react-elements.html)
- [Introducing Relay and GraphQL](https://legacy.reactjs.org/blog/2015/02/20/introducing-relay-and-graphql.html)
- [Introducing React Native](https://legacy.reactjs.org/blog/2015/03/26/introducing-react-native.html)
- [React v0.13.1](https://legacy.reactjs.org/blog/2015/03/16/react-v0.13.1.html)
- [React v0.13.2](https://legacy.reactjs.org/blog/2015/04/18/react-v0.13.2.html)
- [React v0.13.3](https://legacy.reactjs.org/blog/2015/05/08/react-v0.13.3.html)
**Releases**
- [v0.13.3 (May 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.13.2 (April 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.13.1 (March 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.13.0 (March 2015)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 0.12[Link for React 0.12]()
**Blog Posts**
- [React v0.12](https://legacy.reactjs.org/blog/2014/10/28/react-v0.12.html)
- [React v0.12 RC](https://legacy.reactjs.org/blog/2014/10/16/react-v0.12-rc1.html)
- [Introducing React Elements](https://legacy.reactjs.org/blog/2014/10/14/introducing-react-elements.html)
- [React v0.12.2](https://legacy.reactjs.org/blog/2014/12/18/react-v0.12.2.html)
**Releases**
- [v0.12.2 (December 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.12.1 (November 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.12.0 (October 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 0.11[Link for React 0.11]()
**Blog Posts**
- [React v0.11](https://legacy.reactjs.org/blog/2014/07/17/react-v0.11.html)
- [React v0.11 RC](https://legacy.reactjs.org/blog/2014/07/13/react-v0.11-rc1.html)
- [One Year of Open-Source React](https://legacy.reactjs.org/blog/2014/05/29/one-year-of-open-source-react.html)
- [The Road to 1.0](https://legacy.reactjs.org/blog/2014/03/28/the-road-to-1.0.html)
- [React v0.11.1](https://legacy.reactjs.org/blog/2014/07/25/react-v0.11.1.html)
- [React v0.11.2](https://legacy.reactjs.org/blog/2014/09/16/react-v0.11.2.html)
- [Introducing the JSX Specificaion](https://legacy.reactjs.org/blog/2014/09/03/introducing-the-jsx-specification.html)
**Releases**
- [v0.11.2 (September 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.11.1 (July 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.11.0 (July 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### React 0.10 and below[Link for React 0.10 and below]()
**Blog Posts**
- [React v0.10](https://legacy.reactjs.org/blog/2014/03/21/react-v0.10.html)
- [React v0.10 RC](https://legacy.reactjs.org/blog/2014/03/19/react-v0.10-rc1.html)
- [React v0.9](https://legacy.reactjs.org/blog/2014/02/20/react-v0.9.html)
- [React v0.9 RC](https://legacy.reactjs.org/blog/2014/02/16/react-v0.9-rc1.html)
- [React Chrome Developer Tools](https://legacy.reactjs.org/blog/2014/01/02/react-chrome-developer-tools.html)
- [React v0.8](https://legacy.reactjs.org/blog/2013/12/19/react-v0.8.0.html)
- [React v0.5.2, v0.4.2](https://legacy.reactjs.org/blog/2013/12/18/react-v0.5.2-v0.4.2.html)
- [React v0.5.1](https://legacy.reactjs.org/blog/2013/10/29/react-v0-5-1.html)
- [React v0.5](https://legacy.reactjs.org/blog/2013/10/16/react-v0.5.0.html)
- [React v0.4.1](https://legacy.reactjs.org/blog/2013/07/26/react-v0-4-1.html)
- [React v0.4.0](https://legacy.reactjs.org/blog/2013/07/17/react-v0-4-0.html)
- [New in React v0.4: Prop Validation and Default Values](https://legacy.reactjs.org/blog/2013/07/11/react-v0-4-prop-validation-and-default-values.html)
- [New in React v0.4: Autobind by Default](https://legacy.reactjs.org/blog/2013/07/02/react-v0-4-autobind-by-default.html)
- [React v0.3.3](https://legacy.reactjs.org/blog/2013/07/02/react-v0-4-autobind-by-default.html)
**Releases**
- [v0.10.0 (March 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.9.0 (February 2014)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.8.0 (December 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.5.2 (December 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.5.1 (October 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.5.0 (October 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.4.1 (July 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.4.0 (July 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.3.3 (June 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.3.2 (May 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.3.1 (May 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [v0.3.0 (May 2013)](https://github.com/facebook/react/blob/main/CHANGELOG.md)
### Initial Commit[Link for Initial Commit]()
React was open-sourced on May 29, 2013. The initial commit is: [`75897c`: Initial public release](https://github.com/facebook/react/commit/75897c2dcd1dd3a6ca46284dd37e13d22b4b16b4)
See the first blog post: [Why did we build React?](https://legacy.reactjs.org/blog/2013/06/05/why-react.html)
React was open sourced at Facebook Seattle in 2013: |
https://react.dev/community/translations | [Community](https://react.dev/community)
# Translations[Link for this heading]()
React docs are translated by the global community into many languages all over the world.
## Source site[Link for Source site]()
All translations are provided from the canonical source docs:
- [English](https://react.dev/) — [Contribute](https://github.com/reactjs/react.dev/)
## Full translations[Link for Full translations]()
- [French (Français)](https://fr.react.dev/) — [Contribute](https://github.com/reactjs/fr.react.dev)
- [Japanese (日本語)](https://ja.react.dev/) — [Contribute](https://github.com/reactjs/ja.react.dev)
- [Korean (한국어)](https://ko.react.dev/) — [Contribute](https://github.com/reactjs/ko.react.dev)
- [Simplified Chinese (简体中文)](https://zh-hans.react.dev/) — [Contribute](https://github.com/reactjs/zh-hans.react.dev)
- [Spanish (Español)](https://es.react.dev/) — [Contribute](https://github.com/reactjs/es.react.dev)
- [Turkish (Türkçe)](https://tr.react.dev/) — [Contribute](https://github.com/reactjs/tr.react.dev)
## In-progress translations[Link for In-progress translations]()
For the progress of each translation, see: [Is React Translated Yet?](https://translations.react.dev/)
- [Arabic (العربية)](https://ar.react.dev/) — [Contribute](https://github.com/reactjs/ar.react.dev)
- [Azerbaijani (Azərbaycanca)](https://az.react.dev/) — [Contribute](https://github.com/reactjs/az.react.dev)
- [Belarusian (Беларуская)](https://be.react.dev/) — [Contribute](https://github.com/reactjs/be.react.dev)
- [Bengali (বাংলা)](https://bn.react.dev/) — [Contribute](https://github.com/reactjs/bn.react.dev)
- [Czech (Čeština)](https://cs.react.dev/) — [Contribute](https://github.com/reactjs/cs.react.dev)
- [Finnish (Suomi)](https://fi.react.dev/) — [Contribute](https://github.com/reactjs/fi.react.dev)
- [German (Deutsch)](https://de.react.dev/) — [Contribute](https://github.com/reactjs/de.react.dev)
- [Gujarati (ગુજરાતી)](https://gu.react.dev/) — [Contribute](https://github.com/reactjs/gu.react.dev)
- [Hebrew (עברית)](https://he.react.dev/) — [Contribute](https://github.com/reactjs/he.react.dev)
- [Hindi (हिन्दी)](https://hi.react.dev/) — [Contribute](https://github.com/reactjs/hi.react.dev)
- [Hungarian (magyar)](https://hu.react.dev/) — [Contribute](https://github.com/reactjs/hu.react.dev)
- [Icelandic (Íslenska)](https://is.react.dev/) — [Contribute](https://github.com/reactjs/is.react.dev)
- [Indonesian (Bahasa Indonesia)](https://id.react.dev/) — [Contribute](https://github.com/reactjs/id.react.dev)
- [Italian (Italiano)](https://it.react.dev/) — [Contribute](https://github.com/reactjs/it.react.dev)
- [Kazakh (Қазақша)](https://kk.react.dev/) — [Contribute](https://github.com/reactjs/kk.react.dev)
- [Lao (ພາສາລາວ)](https://lo.react.dev/) — [Contribute](https://github.com/reactjs/lo.react.dev)
- [Macedonian (Македонски)](https://mk.react.dev/) — [Contribute](https://github.com/reactjs/mk.react.dev)
- [Malayalam (മലയാളം)](https://ml.react.dev/) — [Contribute](https://github.com/reactjs/ml.react.dev)
- [Mongolian (Монгол хэл)](https://mn.react.dev/) — [Contribute](https://github.com/reactjs/mn.react.dev)
- [Persian (فارسی)](https://fa.react.dev/) — [Contribute](https://github.com/reactjs/fa.react.dev)
- [Polish (Polski)](https://pl.react.dev/) — [Contribute](https://github.com/reactjs/pl.react.dev)
- [Portuguese (Brazil) (Português do Brasil)](https://pt-br.react.dev/) — [Contribute](https://github.com/reactjs/pt-br.react.dev)
- [Russian (Русский)](https://ru.react.dev/) — [Contribute](https://github.com/reactjs/ru.react.dev)
- [Serbian (Srpski)](https://sr.react.dev/) — [Contribute](https://github.com/reactjs/sr.react.dev)
- [Sinhala (සිංහල)](https://si.react.dev/) — [Contribute](https://github.com/reactjs/si.react.dev)
- [Swahili (Kiswahili)](https://sw.react.dev/) — [Contribute](https://github.com/reactjs/sw.react.dev)
- [Tamil (தமிழ்)](https://ta.react.dev/) — [Contribute](https://github.com/reactjs/ta.react.dev)
- [Telugu (తెలుగు)](https://te.react.dev/) — [Contribute](https://github.com/reactjs/te.react.dev)
- [Traditional Chinese (繁體中文)](https://zh-hant.react.dev/) — [Contribute](https://github.com/reactjs/zh-hant.react.dev)
- [Ukrainian (Українська)](https://uk.react.dev/) — [Contribute](https://github.com/reactjs/uk.react.dev)
- [Urdu (اردو)](https://ur.react.dev/) — [Contribute](https://github.com/reactjs/ur.react.dev)
- [Vietnamese (Tiếng Việt)](https://vi.react.dev/) — [Contribute](https://github.com/reactjs/vi.react.dev)
## How to contribute[Link for How to contribute]()
You can contribute to the translation efforts!
The community conducts the translation work for the React docs on each language-specific fork of react.dev. Typical translation work involves directly translating a Markdown file and creating a pull request. Click the “contribute” link above to the GitHub repository for your language, and follow the instructions there to help with the translation effort.
If you want to start a new translation for your language, visit: [translations.react.dev](https://github.com/reactjs/translations.react.dev)
[PreviousDocs Contributors](https://react.dev/community/docs-contributors)
[NextAcknowledgements](https://react.dev/community/acknowledgements) |
https://react.dev/learn | [Learn React](https://react.dev/learn)
# Quick Start[Link for this heading]()
Welcome to the React documentation! This page will give you an introduction to 80% of the React concepts that you will use on a daily basis.
### You will learn
- How to create and nest components
- How to add markup and styles
- How to display data
- How to render conditions and lists
- How to respond to events and update the screen
- How to share data between components
## Creating and nesting components[Link for Creating and nesting components]()
React apps are made out of *components*. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.
React components are JavaScript functions that return markup:
```
function MyButton() {
return (
<button>I'm a button</button>
);
}
```
Now that you’ve declared `MyButton`, you can nest it into another component:
```
export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton />
</div>
);
}
```
Notice that `<MyButton />` starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase.
Have a look at the result:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
function MyButton() {
return (
<button>
I'm a button
</button>
);
}
export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton />
</div>
);
}
```
Show more
The `export default` keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax, [MDN](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) and [javascript.info](https://javascript.info/import-export) have great references.
## Writing markup with JSX[Link for Writing markup with JSX]()
The markup syntax you’ve seen above is called *JSX*. It is optional, but most React projects use JSX for its convenience. All of the [tools we recommend for local development](https://react.dev/learn/installation) support JSX out of the box.
JSX is stricter than HTML. You have to close tags like `<br />`. Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a `<div>...</div>` or an empty `<>...</>` wrapper:
```
function AboutPage() {
return (
<>
<h1>About</h1>
<p>Hello there.<br />How do you do?</p>
</>
);
}
```
If you have a lot of HTML to port to JSX, you can use an [online converter.](https://transform.tools/html-to-jsx)
## Adding styles[Link for Adding styles]()
In React, you specify a CSS class with `className`. It works the same way as the HTML [`class`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class) attribute:
```
<img className="avatar" />
```
Then you write the CSS rules for it in a separate CSS file:
```
/* In your CSS */
.avatar {
border-radius: 50%;
}
```
React does not prescribe how you add CSS files. In the simplest case, you’ll add a [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.
## Displaying data[Link for Displaying data]()
JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display `user.name`:
```
return (
<h1>
{user.name}
</h1>
);
```
You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces *instead of* quotes. For example, `className="avatar"` passes the `"avatar"` string as the CSS class, but `src={user.imageUrl}` reads the JavaScript `user.imageUrl` variable value, and then passes that value as the `src` attribute:
```
return (
<img
className="avatar"
src={user.imageUrl}
/>
);
```
You can put more complex expressions inside the JSX curly braces too, for example, [string concatenation](https://javascript.info/operators):
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
const user = {
name: 'Hedy Lamarr',
imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',
imageSize: 90,
};
export default function Profile() {
return (
<>
<h1>{user.name}</h1>
<img
className="avatar"
src={user.imageUrl}
alt={'Photo of ' + user.name}
style={{
width: user.imageSize,
height: user.imageSize
}}
/>
</>
);
}
```
Show more
In the above example, `style={{}}` is not a special syntax, but a regular `{}` object inside the `style={ }` JSX curly braces. You can use the `style` attribute when your styles depend on JavaScript variables.
## Conditional rendering[Link for Conditional rendering]()
In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use an [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) statement to conditionally include JSX:
```
let content;
if (isLoggedIn) {
content = <AdminPanel />;
} else {
content = <LoginForm />;
}
return (
<div>
{content}
</div>
);
```
If you prefer more compact code, you can use the [conditional `?` operator.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) Unlike `if`, it works inside JSX:
```
<div>
{isLoggedIn ? (
<AdminPanel />
) : (
<LoginForm />
)}
</div>
```
When you don’t need the `else` branch, you can also use a shorter [logical `&&` syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND):
```
<div>
{isLoggedIn && <AdminPanel />}
</div>
```
All of these approaches also work for conditionally specifying attributes. If you’re unfamiliar with some of this JavaScript syntax, you can start by always using `if...else`.
## Rendering lists[Link for Rendering lists]()
You will rely on JavaScript features like [`for` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) and the [array `map()` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to render lists of components.
For example, let’s say you have an array of products:
```
const products = [
{ title: 'Cabbage', id: 1 },
{ title: 'Garlic', id: 2 },
{ title: 'Apple', id: 3 },
];
```
Inside your component, use the `map()` function to transform an array of products into an array of `<li>` items:
```
const listItems = products.map(product =>
<li key={product.id}>
{product.title}
</li>
);
return (
<ul>{listItems}</ul>
);
```
Notice how `<li>` has a `key` attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
const products = [
{ title: 'Cabbage', isFruit: false, id: 1 },
{ title: 'Garlic', isFruit: false, id: 2 },
{ title: 'Apple', isFruit: true, id: 3 },
];
export default function ShoppingList() {
const listItems = products.map(product =>
<li
key={product.id}
style={{
color: product.isFruit ? 'magenta' : 'darkgreen'
}}
>
{product.title}
</li>
);
return (
<ul>{listItems}</ul>
);
}
```
Show more
## Responding to events[Link for Responding to events]()
You can respond to events by declaring *event handler* functions inside your components:
```
function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
```
Notice how `onClick={handleClick}` has no parentheses at the end! Do not *call* the event handler function: you only need to *pass it down*. React will call your event handler when the user clicks the button.
## Updating the screen[Link for Updating the screen]()
Often, you’ll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add *state* to your component.
First, import [`useState`](https://react.dev/reference/react/useState) from React:
```
import { useState } from 'react';
```
Now you can declare a *state variable* inside your component:
```
function MyButton() {
const [count, setCount] = useState(0);
// ...
```
You’ll get two things from `useState`: the current state (`count`), and the function that lets you update it (`setCount`). You can give them any names, but the convention is to write `[something, setSomething]`.
The first time the button is displayed, `count` will be `0` because you passed `0` to `useState()`. When you want to change state, call `setCount()` and pass the new value to it. Clicking this button will increment the counter:
```
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}
```
React will call your component function again. This time, `count` will be `1`. Then it will be `2`. And so on.
If you render the same component multiple times, each will get its own state. Click each button separately:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function MyApp() {
return (
<div>
<h1>Counters that update separately</h1>
<MyButton />
<MyButton />
</div>
);
}
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}
```
Show more
Notice how each button “remembers” its own `count` state and doesn’t affect other buttons.
## Using Hooks[Link for Using Hooks]()
Functions starting with `use` are called *Hooks*. `useState` is a built-in Hook provided by React. You can find other built-in Hooks in the [API reference.](https://react.dev/reference/react) You can also write your own Hooks by combining the existing ones.
Hooks are more restrictive than other functions. You can only call Hooks *at the top* of your components (or other Hooks). If you want to use `useState` in a condition or a loop, extract a new component and put it there.
## Sharing data between components[Link for Sharing data between components]()
In the previous example, each `MyButton` had its own independent `count`, and when each button was clicked, only the `count` for the button clicked changed:
![Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. Both MyButton components contain a count with value zero.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_child.dark.png&w=828&q=75)
![Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. Both MyButton components contain a count with value zero.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_child.png&w=828&q=75)
Initially, each `MyButton`’s `count` state is `0`
![The same diagram as the previous, with the count of the first child MyButton component highlighted indicating a click with the count value incremented to one. The second MyButton component still contains value zero.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_child_clicked.dark.png&w=828&q=75)
![The same diagram as the previous, with the count of the first child MyButton component highlighted indicating a click with the count value incremented to one. The second MyButton component still contains value zero.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_child_clicked.png&w=828&q=75)
The first `MyButton` updates its `count` to `1`
However, often you’ll need components to *share data and always update together*.
To make both `MyButton` components display the same `count` and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them.
In this example, it is `MyApp`:
![Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. MyApp contains a count value of zero which is passed down to both of the MyButton components, which also show value zero.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_parent.dark.png&w=828&q=75)
![Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. MyApp contains a count value of zero which is passed down to both of the MyButton components, which also show value zero.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_parent.png&w=828&q=75)
Initially, `MyApp`’s `count` state is `0` and is passed down to both children
![The same diagram as the previous, with the count of the parent MyApp component highlighted indicating a click with the value incremented to one. The flow to both of the children MyButton components is also highlighted, and the count value in each child is set to one indicating the value was passed down.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_parent_clicked.dark.png&w=828&q=75)
![The same diagram as the previous, with the count of the parent MyApp component highlighted indicating a click with the value incremented to one. The flow to both of the children MyButton components is also highlighted, and the count value in each child is set to one indicating the value was passed down.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_parent_clicked.png&w=828&q=75)
On click, `MyApp` updates its `count` state to `1` and passes it down to both children
Now when you click either button, the `count` in `MyApp` will change, which will change both of the counts in `MyButton`. Here’s how you can express this in code.
First, *move the state up* from `MyButton` into `MyApp`:
```
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update separately</h1>
<MyButton />
<MyButton />
</div>
);
}
function MyButton() {
// ... we're moving code from here ...
}
```
Then, *pass the state down* from `MyApp` to each `MyButton`, together with the shared click handler. You can pass information to `MyButton` using the JSX curly braces, just like you previously did with built-in tags like `<img>`:
```
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
```
The information you pass down like this is called *props*. Now the `MyApp` component contains the `count` state and the `handleClick` event handler, and *passes both of them down as props* to each of the buttons.
Finally, change `MyButton` to *read* the props you have passed from its parent component:
```
function MyButton({ count, onClick }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}
```
When you click the button, the `onClick` handler fires. Each button’s `onClick` prop was set to the `handleClick` function inside `MyApp`, so the code inside of it runs. That code calls `setCount(count + 1)`, incrementing the `count` state variable. The new `count` value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”. By moving state up, you’ve shared it between components.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
function MyButton({ count, onClick }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}
```
Show more
## Next Steps[Link for Next Steps]()
By now, you know the basics of how to write React code!
Check out the [Tutorial](https://react.dev/learn/tutorial-tic-tac-toe) to put them into practice and build your first mini-app with React.
[NextTutorial: Tic-Tac-Toe](https://react.dev/learn/tutorial-tic-tac-toe) |
https://react.dev/learn/add-react-to-an-existing-project | [Learn React](https://react.dev/learn)
[Installation](https://react.dev/learn/installation)
# Add React to an Existing Project[Link for this heading]()
If you want to add some interactivity to your existing project, you don’t have to rewrite it in React. Add React to your existing stack, and render interactive React components anywhere.
### Note
**You need to install [Node.js](https://nodejs.org/en/) for local development.** Although you can [try React](https://react.dev/learn/installation) online or with a simple HTML page, realistically most JavaScript tooling you’ll want to use for development requires Node.js.
## Using React for an entire subroute of your existing website[Link for Using React for an entire subroute of your existing website]()
Let’s say you have an existing web app at `example.com` built with another server technology (like Rails), and you want to implement all routes starting with `example.com/some-app/` fully with React.
Here’s how we recommend to set it up:
1. **Build the React part of your app** using one of the [React-based frameworks](https://react.dev/learn/start-a-new-react-project).
2. **Specify `/some-app` as the *base path*** in your framework’s configuration (here’s how: [Next.js](https://nextjs.org/docs/api-reference/next.config.js/basepath), [Gatsby](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/path-prefix/)).
3. **Configure your server or a proxy** so that all requests under `/some-app/` are handled by your React app.
This ensures the React part of your app can [benefit from the best practices](https://react.dev/learn/start-a-new-react-project) baked into those frameworks.
Many React-based frameworks are full-stack and let your React app take advantage of the server. However, you can use the same approach even if you can’t or don’t want to run JavaScript on the server. In that case, serve the HTML/CSS/JS export ([`next export` output](https://nextjs.org/docs/advanced-features/static-html-export) for Next.js, default for Gatsby) at `/some-app/` instead.
## Using React for a part of your existing page[Link for Using React for a part of your existing page]()
Let’s say you have an existing page built with another technology (either a server one like Rails, or a client one like Backbone), and you want to render interactive React components somewhere on that page. That’s a common way to integrate React—in fact, it’s how most React usage looked at Meta for many years!
You can do this in two steps:
1. **Set up a JavaScript environment** that lets you use the [JSX syntax](https://react.dev/learn/writing-markup-with-jsx), split your code into modules with the [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) / [`export`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) syntax, and use packages (for example, React) from the [npm](https://www.npmjs.com/) package registry.
2. **Render your React components** where you want to see them on the page.
The exact approach depends on your existing page setup, so let’s walk through some details.
### Step 1: Set up a modular JavaScript environment[Link for Step 1: Set up a modular JavaScript environment]()
A modular JavaScript environment lets you write your React components in individual files, as opposed to writing all of your code in a single file. It also lets you use all the wonderful packages published by other developers on the [npm](https://www.npmjs.com/) registry—including React itself! How you do this depends on your existing setup:
- **If your app is already split into files that use `import` statements,** try to use the setup you already have. Check whether writing `<div />` in your JS code causes a syntax error. If it causes a syntax error, you might need to [transform your JavaScript code with Babel](https://babeljs.io/setup), and enable the [Babel React preset](https://babeljs.io/docs/babel-preset-react) to use JSX.
- **If your app doesn’t have an existing setup for compiling JavaScript modules,** set it up with [Vite](https://vitejs.dev/). The Vite community maintains [many integrations with backend frameworks](https://github.com/vitejs/awesome-vite), including Rails, Django, and Laravel. If your backend framework is not listed, [follow this guide](https://vitejs.dev/guide/backend-integration.html) to manually integrate Vite builds with your backend.
To check whether your setup works, run this command in your project folder:
Terminal
Copy
npm install react react-dom
Then add these lines of code at the top of your main JavaScript file (it might be called `index.js` or `main.js`):
index.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from 'react-dom/client';
// Clear the existing HTML content
document.body.innerHTML = '<div id="app"></div>';
// Render your React component instead
const root = createRoot(document.getElementById('app'));
root.render(<h1>Hello, world</h1>);
```
If the entire content of your page was replaced by a “Hello, world!”, everything worked! Keep reading.
### Note
Integrating a modular JavaScript environment into an existing project for the first time can feel intimidating, but it’s worth it! If you get stuck, try our [community resources](https://react.dev/community) or the [Vite Chat](https://chat.vitejs.dev/).
### Step 2: Render React components anywhere on the page[Link for Step 2: Render React components anywhere on the page]()
In the previous step, you put this code at the top of your main file:
```
import { createRoot } from 'react-dom/client';
// Clear the existing HTML content
document.body.innerHTML = '<div id="app"></div>';
// Render your React component instead
const root = createRoot(document.getElementById('app'));
root.render(<h1>Hello, world</h1>);
```
Of course, you don’t actually want to clear the existing HTML content!
Delete this code.
Instead, you probably want to render your React components in specific places in your HTML. Open your HTML page (or the server templates that generate it) and add a unique [`id`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) attribute to any tag, for example:
```
<!-- ... somewhere in your html ... -->
<nav id="navigation"></nav>
<!-- ... more html ... -->
```
This lets you find that HTML element with [`document.getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) and pass it to [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) so that you can render your own React component inside:
index.jsindex.html
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from 'react-dom/client';
function NavigationBar() {
// TODO: Actually implement a navigation bar
return <h1>Hello from React!</h1>;
}
const domNode = document.getElementById('navigation');
const root = createRoot(domNode);
root.render(<NavigationBar />);
```
Notice how the original HTML content from `index.html` is preserved, but your own `NavigationBar` React component now appears inside the `<nav id="navigation">` from your HTML. Read the [`createRoot` usage documentation](https://react.dev/reference/react-dom/client/createRoot) to learn more about rendering React components inside an existing HTML page.
When you adopt React in an existing project, it’s common to start with small interactive components (like buttons), and then gradually keep “moving upwards” until eventually your entire page is built with React. If you ever reach that point, we recommend migrating to [a React framework](https://react.dev/learn/start-a-new-react-project) right after to get the most out of React.
## Using React Native in an existing native mobile app[Link for Using React Native in an existing native mobile app]()
[React Native](https://reactnative.dev/) can also be integrated into existing native apps incrementally. If you have an existing native app for Android (Java or Kotlin) or iOS (Objective-C or Swift), [follow this guide](https://reactnative.dev/docs/integration-with-existing-apps) to add a React Native screen to it.
[PreviousStart a New React Project](https://react.dev/learn/start-a-new-react-project)
[NextEditor Setup](https://react.dev/learn/editor-setup) |
https://react.dev/ | ![logo by @sawaratsuki1004](/_next/image?url=%2Fimages%2Fuwu.png&w=640&q=75 "logo by @sawaratsuki1004")
# React
The library for web and native user interfaces
[Learn React](https://react.dev/learn)[API Reference](https://react.dev/reference/react)
## Create user interfaces from components
React lets you build user interfaces out of individual pieces called components. Create your own React components like `Thumbnail`, `LikeButton`, and `Video`. Then combine them into entire screens, pages, and apps.
### Video.js
```
function Video({ video }) {
return (
<div>
<Thumbnail video={video} />
<a href={video.url}>
<h3>{video.title}</h3>
<p>{video.description}</p>
</a>
<LikeButton video={video} />
</div>
);
}
```
[]()[**My video**
\
Video description]()
Whether you work on your own or with thousands of other developers, using React feels the same. It is designed to let you seamlessly combine components written by independent people, teams, and organizations.
## Write components with code and markup
React components are JavaScript functions. Want to show some content conditionally? Use an `if` statement. Displaying a list? Try array `map()`. Learning React is learning programming.
### VideoList.js
```
function VideoList({ videos, emptyHeading }) {
const count = videos.length;
let heading = emptyHeading;
if (count > 0) {
const noun = count > 1 ? 'Videos' : 'Video';
heading = count + ' ' + noun;
}
return (
<section>
<h2>{heading}</h2>
{videos.map(video =>
<Video key={video.id} video={video} />
)}
</section>
);
}
```
## 3 Videos
[]()[**First video**
\
Video description]()
[]()[**Second video**
\
Video description]()
[]()[**Third video**
\
Video description]()
This markup syntax is called JSX. It is a JavaScript syntax extension popularized by React. Putting JSX markup close to related rendering logic makes React components easy to create, maintain, and delete.
## Add interactivity wherever you need it
React components receive data and return what should appear on the screen. You can pass them new data in response to an interaction, like when the user types into an input. React will then update the screen to match the new data.
### SearchableVideoList.js
```
import { useState } from 'react';
function SearchableVideoList({ videos }) {
const [searchText, setSearchText] = useState('');
const foundVideos = filterVideos(videos, searchText);
return (
<>
<SearchInput
value={searchText}
onChange={newText => setSearchText(newText)} />
<VideoList
videos={foundVideos}
emptyHeading={`No matches for “${searchText}”`} />
</>
);
}
```
example.com/videos.html
# React Videos
A brief history of React
Search
## 5 Videos
[](https://www.youtube.com/watch?v=8pDqJVdNa44)[**React: The Documentary**
\
The origin story of React](https://www.youtube.com/watch?v=8pDqJVdNa44)
[](https://www.youtube.com/watch?v=x7cQ3mrcKaY)[**Rethinking Best Practices**
\
Pete Hunt (2013)](https://www.youtube.com/watch?v=x7cQ3mrcKaY)
[](https://www.youtube.com/watch?v=KVZ-P-ZI6W4)[**Introducing React Native**
\
Tom Occhino (2015)](https://www.youtube.com/watch?v=KVZ-P-ZI6W4)
[](https://www.youtube.com/watch?v=V-QO-KO90iQ)[**Introducing React Hooks**
\
Sophie Alpert and Dan Abramov (2018)](https://www.youtube.com/watch?v=V-QO-KO90iQ)
[](https://www.youtube.com/watch?v=TQQPAU21ZUw)[**Introducing Server Components**
\
Dan Abramov and Lauren Tan (2020)](https://www.youtube.com/watch?v=TQQPAU21ZUw)
You don’t have to build your whole page in React. Add React to your existing HTML page, and render interactive React components anywhere on it.
[Add React to your page](https://react.dev/learn/add-react-to-an-existing-project)
## Go full-stack with a framework
React is a library. It lets you put components together, but it doesn’t prescribe how to do routing and data fetching. To build an entire app with React, we recommend a full-stack React framework like [Next.js](https://nextjs.org) or [Remix](https://remix.run).
### confs/\[slug].js
```
import { db } from './database.js';
import { Suspense } from 'react';
async function ConferencePage({ slug }) {
const conf = await db.Confs.find({ slug });
return (
<ConferenceLayout conf={conf}>
<Suspense fallback={<TalksLoading />}>
<Talks confId={conf.id} />
</Suspense>
</ConferenceLayout>
);
}
async function Talks({ confId }) {
const talks = await db.Talks.findAll({ confId });
const videos = talks.map(talk => talk.video);
return <SearchableVideoList videos={videos} />;
}
```
example.com/confs/react-conf-2021
React Conf 2021React Conf 2019
![](/images/home/conf2021/cover.svg)
Search
## 19 Videos
[![](/images/home/conf2021/andrew.jpg)![](/images/home/conf2021/lauren.jpg)![](/images/home/conf2021/juan.jpg)![](/images/home/conf2021/rick.jpg)
\
React Conf](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=1)
[**React 18 Keynote**
\
The React Team](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=1)
[![](/images/home/conf2021/shruti.jpg)
\
React Conf](https://www.youtube.com/watch?v=ytudH8je5ko&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=2)
[**React 18 for App Developers**
\
Shruti Kapoor](https://www.youtube.com/watch?v=ytudH8je5ko&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=2)
[![](/images/home/conf2021/shaundai.jpg)
\
React Conf](https://www.youtube.com/watch?v=pj5N-Khihgc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=3)
[**Streaming Server Rendering with Suspense**
\
Shaundai Person](https://www.youtube.com/watch?v=pj5N-Khihgc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=3)
[![](/images/home/conf2021/aakansha.jpg)
\
React Conf](https://www.youtube.com/watch?v=qn7gRClrC9U&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=4)
[**The First React Working Group**
\
Aakansha Doshi](https://www.youtube.com/watch?v=qn7gRClrC9U&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=4)
[![](/images/home/conf2021/brian.jpg)
\
React Conf](https://www.youtube.com/watch?v=oxDfrke8rZg&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=5)
[**React Developer Tooling**
\
Brian Vaughn](https://www.youtube.com/watch?v=oxDfrke8rZg&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=5)
[![](/images/home/conf2021/xuan.jpg)
\
React Conf](https://www.youtube.com/watch?v=lGEMwh32soc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=6)
[**React without memo**
\
Xuan Huang (黄玄)](https://www.youtube.com/watch?v=lGEMwh32soc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=6)
[![](/images/home/conf2021/rachel.jpg)
\
React Conf](https://www.youtube.com/watch?v=mneDaMYOKP8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=7)
[**React Docs Keynote**
\
Rachel Nabors](https://www.youtube.com/watch?v=mneDaMYOKP8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=7)
[![](/images/home/conf2021/debbie.jpg)
\
React Conf](https://www.youtube.com/watch?v=-7odLW_hG7s&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=8)
[**Things I Learnt from the New React Docs**
\
Debbie O'Brien](https://www.youtube.com/watch?v=-7odLW_hG7s&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=8)
[![](/images/home/conf2021/sarah.jpg)
\
React Conf](https://www.youtube.com/watch?v=5X-WEQflCL0&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=9)
[**Learning in the Browser**
\
Sarah Rainsberger](https://www.youtube.com/watch?v=5X-WEQflCL0&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=9)
[![](/images/home/conf2021/linton.jpg)
\
React Conf](https://www.youtube.com/watch?v=7cPWmID5XAk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=10)
[**The ROI of Designing with React**
\
Linton Ye](https://www.youtube.com/watch?v=7cPWmID5XAk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=10)
[![](/images/home/conf2021/delba.jpg)
\
React Conf](https://www.youtube.com/watch?v=zL8cz2W0z34&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=11)
[**Interactive Playgrounds with React**
\
Delba de Oliveira](https://www.youtube.com/watch?v=zL8cz2W0z34&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=11)
[![](/images/home/conf2021/robert.jpg)
\
React Conf](https://www.youtube.com/watch?v=lhVGdErZuN4&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=12)
[**Re-introducing Relay**
\
Robert Balicki](https://www.youtube.com/watch?v=lhVGdErZuN4&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=12)
[![](/images/home/conf2021/eric.jpg)![](/images/home/conf2021/steven.jpg)
\
React Conf](https://www.youtube.com/watch?v=9L4FFrvwJwY&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=13)
[**React Native Desktop**
\
Eric Rozell and Steven Moyes](https://www.youtube.com/watch?v=9L4FFrvwJwY&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=13)
[![](/images/home/conf2021/roman.jpg)
\
React Conf](https://www.youtube.com/watch?v=NLj73vrc2I8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=14)
[**On-device Machine Learning for React Native**
\
Roman Rädle](https://www.youtube.com/watch?v=NLj73vrc2I8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=14)
[![](/images/home/conf2021/daishi.jpg)
\
React Conf](https://www.youtube.com/watch?v=oPfSC5bQPR8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=15)
[**React 18 for External Store Libraries**
\
Daishi Kato](https://www.youtube.com/watch?v=oPfSC5bQPR8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=15)
[![](/images/home/conf2021/diego.jpg)
\
React Conf](https://www.youtube.com/watch?v=dcm8fjBfro8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=16)
[**Building Accessible Components with React 18**
\
Diego Haz](https://www.youtube.com/watch?v=dcm8fjBfro8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=16)
[![](/images/home/conf2021/tafu.jpg)
\
React Conf](https://www.youtube.com/watch?v=S4a0QlsH0pU&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=17)
[**Accessible Japanese Form Components with React**
\
Tafu Nakazaki](https://www.youtube.com/watch?v=S4a0QlsH0pU&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=17)
[![](/images/home/conf2021/lyle.jpg)
\
React Conf](https://www.youtube.com/watch?v=b3l4WxipFsE&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=18)
[**UI Tools for Artists**
\
Lyle Troxell](https://www.youtube.com/watch?v=b3l4WxipFsE&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=18)
[![](/images/home/conf2021/helen.jpg)
\
React Conf](https://www.youtube.com/watch?v=HS6vIYkSNks&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=19)
[**Hydrogen + React 18**
\
Helen Lin](https://www.youtube.com/watch?v=HS6vIYkSNks&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=19)
React is also an architecture. Frameworks that implement it let you fetch data in asynchronous components that run on the server or even during the build. Read data from a file or a database, and pass it down to your interactive components.
[Get started with a framework](https://react.dev/learn/start-a-new-react-project)
## Use the best from every platform
People love web and native apps for different reasons. React lets you build both web apps and native apps using the same skills. It leans upon each platform’s unique strengths to let your interfaces feel just right on every platform.
example.com
#### Stay true to the web
People expect web app pages to load fast. On the server, React lets you start streaming HTML while you’re still fetching data, progressively filling in the remaining content before any JavaScript code loads. On the client, React can use standard web APIs to keep your UI responsive even in the middle of rendering.
12:23 PM
#### Go truly native
People expect native apps to look and feel like their platform. [React Native](https://reactnative.dev) and [Expo](https://github.com/expo/expo) let you build apps in React for Android, iOS, and more. They look and feel native because their UIs *are* truly native. It’s not a web view—your React components render real Android and iOS views provided by the platform.
With React, you can be a web *and* a native developer. Your team can ship to many platforms without sacrificing the user experience. Your organization can bridge the platform silos, and form teams that own entire features end-to-end.
[Build for native platforms](https://reactnative.dev/)
## Upgrade when the future is ready
React approaches changes with care. Every React commit is tested on business-critical surfaces with over a billion users. Over 100,000 React components at Meta help validate every migration strategy.
The React team is always researching how to improve React. Some research takes years to pay off. React has a high bar for taking a research idea into production. Only proven approaches become a part of React.
[Read more React news](https://react.dev/blog)
Latest React News
[**React 19**
\
December 05, 2024](https://react.dev/blog/2024/12/05/react-19)
[**React Compiler Beta Release and Roadmap**
\
October 21, 2024](https://react.dev/blog/2024/10/21/react-compiler-beta-release)
[**React Conf 2024 Recap**
\
May 22, 2024](https://react.dev/blog/2024/05/22/react-conf-2024-recap)
[**React 19 RC**
\
April 25, 2024](https://react.dev/blog/2024/04/25/react-19)
[Read more React news](https://react.dev/blog)
## Join a community of millions
You’re not alone. Two million developers from all over the world visit the React docs every month. React is something that people and teams can agree on.
![People singing karaoke at React Conf](/images/home/community/react_conf_fun.webp)
![Sunil Pai speaking at React India](/images/home/community/react_india_sunil.webp)
![A hallway conversation between two people at React Conf](/images/home/community/react_conf_hallway.webp)
![A hallway conversation at React India](/images/home/community/react_india_hallway.webp)
![Elizabet Oliveira speaking at React Conf](/images/home/community/react_conf_elizabet.webp)
![People taking a group selfie at React India](/images/home/community/react_india_selfie.webp)
![Nat Alison speaking at React Conf](/images/home/community/react_conf_nat.webp)
![Organizers greeting attendees at React India](/images/home/community/react_india_team.webp)
![People singing karaoke at React Conf](/images/home/community/react_conf_fun.webp)
![Sunil Pai speaking at React India](/images/home/community/react_india_sunil.webp)
![A hallway conversation between two people at React Conf](/images/home/community/react_conf_hallway.webp)
![A hallway conversation at React India](/images/home/community/react_india_hallway.webp)
![Elizabet Oliveira speaking at React Conf](/images/home/community/react_conf_elizabet.webp)
![People taking a group selfie at React India](/images/home/community/react_india_selfie.webp)
![Nat Alison speaking at React Conf](/images/home/community/react_conf_nat.webp)
![Organizers greeting attendees at React India](/images/home/community/react_india_team.webp)
This is why React is more than a library, an architecture, or even an ecosystem. React is a community. It’s a place where you can ask for help, find opportunities, and meet new friends. You will meet both developers and designers, beginners and experts, researchers and artists, teachers and students. Our backgrounds may be very different, but React lets us all create user interfaces together.
![logo by @sawaratsuki1004](/images/uwu.png "logo by @sawaratsuki1004")
## Welcome to the React community
[Get Started](https://react.dev/learn) |
https://react.dev/learn/start-a-new-react-project | [Learn React](https://react.dev/learn)
[Installation](https://react.dev/learn/installation)
# Start a New React Project[Link for this heading]()
If you want to build a new app or a new website fully with React, we recommend picking one of the React-powered frameworks popular in the community.
You can use React without a framework, however we’ve found that most apps and sites eventually build solutions to common problems such as code-splitting, routing, data fetching, and generating HTML. These problems are common to all UI libraries, not just React.
By starting with a framework, you can get started with React quickly, and avoid essentially building your own framework later.
##### Deep Dive
#### Can I use React without a framework?[Link for Can I use React without a framework?]()
Show Details
You can definitely use React without a framework—that’s how you’d [use React for a part of your page.](https://react.dev/learn/add-react-to-an-existing-project) **However, if you’re building a new app or a site fully with React, we recommend using a framework.**
Here’s why.
Even if you don’t need routing or data fetching at first, you’ll likely want to add some libraries for them. As your JavaScript bundle grows with every new feature, you might have to figure out how to split code for every route individually. As your data fetching needs get more complex, you are likely to encounter server-client network waterfalls that make your app feel very slow. As your audience includes more users with poor network conditions and low-end devices, you might need to generate HTML from your components to display content early—either on the server, or during the build time. Changing your setup to run some of your code on the server or during the build can be very tricky.
**These problems are not React-specific. This is why Svelte has SvelteKit, Vue has Nuxt, and so on.** To solve these problems on your own, you’ll need to integrate your bundler with your router and with your data fetching library. It’s not hard to get an initial setup working, but there are a lot of subtleties involved in making an app that loads quickly even as it grows over time. You’ll want to send down the minimal amount of app code but do so in a single client–server roundtrip, in parallel with any data required for the page. You’ll likely want the page to be interactive before your JavaScript code even runs, to support progressive enhancement. You may want to generate a folder of fully static HTML files for your marketing pages that can be hosted anywhere and still work with JavaScript disabled. Building these capabilities yourself takes real work.
**React frameworks on this page solve problems like these by default, with no extra work from your side.** They let you start very lean and then scale your app with your needs. Each React framework has a community, so finding answers to questions and upgrading tooling is easier. Frameworks also give structure to your code, helping you and others retain context and skills between different projects. Conversely, with a custom setup it’s easier to get stuck on unsupported dependency versions, and you’ll essentially end up creating your own framework—albeit one with no community or upgrade path (and if it’s anything like the ones we’ve made in the past, more haphazardly designed).
If your app has unusual constraints not served well by these frameworks, or you prefer to solve these problems yourself, you can roll your own custom setup with React. Grab `react` and `react-dom` from npm, set up your custom build process with a bundler like [Vite](https://vitejs.dev/) or [Parcel](https://parceljs.org/), and add other tools as you need them for routing, static generation or server-side rendering, and more.
## Production-grade React frameworks[Link for Production-grade React frameworks]()
These frameworks support all the features you need to deploy and scale your app in production and are working towards supporting our [full-stack architecture vision](). All of the frameworks we recommend are open source with active communities for support, and can be deployed to your own server or a hosting provider. If you’re a framework author interested in being included on this list, [please let us know](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A%20framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A%20).
### Next.js[Link for Next.js]()
**[Next.js’ Pages Router](https://nextjs.org/) is a full-stack React framework.** It’s versatile and lets you create React apps of any size—from a mostly static blog to a complex dynamic application. To create a new Next.js project, run in your terminal:
Terminal
Copy
npx create-next-app@latest
If you’re new to Next.js, check out the [learn Next.js course.](https://nextjs.org/learn)
Next.js is maintained by [Vercel](https://vercel.com/). You can [deploy a Next.js app](https://nextjs.org/docs/app/building-your-application/deploying) to any Node.js or serverless hosting, or to your own server. Next.js also supports a [static export](https://nextjs.org/docs/pages/building-your-application/deploying/static-exports) which doesn’t require a server.
### Remix[Link for Remix]()
**[Remix](https://remix.run/) is a full-stack React framework with nested routing.** It lets you break your app into nested parts that can load data in parallel and refresh in response to the user actions. To create a new Remix project, run:
Terminal
Copy
npx create-remix
If you’re new to Remix, check out the Remix [blog tutorial](https://remix.run/docs/en/main/tutorials/blog) (short) and [app tutorial](https://remix.run/docs/en/main/tutorials/jokes) (long).
Remix is maintained by [Shopify](https://www.shopify.com/). When you create a Remix project, you need to [pick your deployment target](https://remix.run/docs/en/main/guides/deployment). You can deploy a Remix app to any Node.js or serverless hosting by using or writing an [adapter](https://remix.run/docs/en/main/other-api/adapter).
### Gatsby[Link for Gatsby]()
**[Gatsby](https://www.gatsbyjs.com/) is a React framework for fast CMS-backed websites.** Its rich plugin ecosystem and its GraphQL data layer simplify integrating content, APIs, and services into one website. To create a new Gatsby project, run:
Terminal
Copy
npx create-gatsby
If you’re new to Gatsby, check out the [Gatsby tutorial.](https://www.gatsbyjs.com/docs/tutorial/)
Gatsby is maintained by [Netlify](https://www.netlify.com/). You can [deploy a fully static Gatsby site](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting) to any static hosting. If you opt into using server-only features, make sure your hosting provider supports them for Gatsby.
### Expo (for native apps)[Link for Expo (for native apps)]()
**[Expo](https://expo.dev/) is a React framework that lets you create universal Android, iOS, and web apps with truly native UIs.** It provides an SDK for [React Native](https://reactnative.dev/) that makes the native parts easier to use. To create a new Expo project, run:
Terminal
Copy
npx create-expo-app
If you’re new to Expo, check out the [Expo tutorial](https://docs.expo.dev/tutorial/introduction/).
Expo is maintained by [Expo (the company)](https://expo.dev/about). Building apps with Expo is free, and you can submit them to the Google and Apple app stores without restrictions. Expo additionally provides opt-in paid cloud services.
## Bleeding-edge React frameworks[Link for Bleeding-edge React frameworks]()
As we’ve explored how to continue improving React, we realized that integrating React more closely with frameworks (specifically, with routing, bundling, and server technologies) is our biggest opportunity to help React users build better apps. The Next.js team has agreed to collaborate with us in researching, developing, integrating, and testing framework-agnostic bleeding-edge React features like [React Server Components.](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023)
These features are getting closer to being production-ready every day, and we’ve been in talks with other bundler and framework developers about integrating them. Our hope is that in a year or two, all frameworks listed on this page will have full support for these features. (If you’re a framework author interested in partnering with us to experiment with these features, please let us know!)
### Next.js (App Router)[Link for Next.js (App Router)]()
**[Next.js’s App Router](https://nextjs.org/docs) is a redesign of the Next.js APIs aiming to fulfill the React team’s full-stack architecture vision.** It lets you fetch data in asynchronous components that run on the server or even during the build.
Next.js is maintained by [Vercel](https://vercel.com/). You can [deploy a Next.js app](https://nextjs.org/docs/app/building-your-application/deploying) to any Node.js or serverless hosting, or to your own server. Next.js also supports [static export](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) which doesn’t require a server.
##### Deep Dive
#### Which features make up the React team’s full-stack architecture vision?[Link for Which features make up the React team’s full-stack architecture vision?]()
Show Details
Next.js’s App Router bundler fully implements the official [React Server Components specification](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). This lets you mix build-time, server-only, and interactive components in a single React tree.
For example, you can write a server-only React component as an `async` function that reads from a database or from a file. Then you can pass data down from it to your interactive components:
```
// This component runs *only* on the server (or during the build).
async function Talks({ confId }) {
// 1. You're on the server, so you can talk to your data layer. API endpoint not required.
const talks = await db.Talks.findAll({ confId });
// 2. Add any amount of rendering logic. It won't make your JavaScript bundle larger.
const videos = talks.map(talk => talk.video);
// 3. Pass the data down to the components that will run in the browser.
return <SearchableVideoList videos={videos} />;
}
```
Next.js’s App Router also integrates [data fetching with Suspense](https://react.dev/blog/2022/03/29/react-v18). This lets you specify a loading state (like a skeleton placeholder) for different parts of your user interface directly in your React tree:
```
<Suspense fallback={<TalksLoading />}>
<Talks confId={conf.id} />
</Suspense>
```
Server Components and Suspense are React features rather than Next.js features. However, adopting them at the framework level requires buy-in and non-trivial implementation work. At the moment, the Next.js App Router is the most complete implementation. The React team is working with bundler developers to make these features easier to implement in the next generation of frameworks.
[PreviousInstallation](https://react.dev/learn/installation)
[NextAdd React to an Existing Project](https://react.dev/learn/add-react-to-an-existing-project) |
https://react.dev/blog/2024/05/22/react-conf-2024-recap | [Blog](https://react.dev/blog)
# React Conf 2024 Recap[Link for this heading]()
May 22, 2024 by [Ricky Hanlon](https://twitter.com/rickhanlonii).
* * *
Last week we hosted React Conf 2024, a two-day conference in Henderson, Nevada where 700+ attendees gathered in-person to discuss the latest in UI engineering. This was our first in-person conference since 2019, and we were thrilled to be able to bring the community together again.
* * *
At React Conf 2024, we announced the [React 19 RC](https://react.dev/blog/2024/12/05/react-19), the [React Native New Architecture Beta](https://github.com/reactwg/react-native-new-architecture/discussions/189), and an experimental release of the [React Compiler](https://react.dev/learn/react-compiler). The community also took the stage to announce [React Router v7](https://remix.run/blog/merging-remix-and-react-router), [Universal Server Components](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=20765s) in Expo Router, React Server Components in [RedwoodJS](https://redwoodjs.com/blog/rsc-now-in-redwoodjs), and much more.
The entire [day 1](https://www.youtube.com/watch?v=T8TZQ6k4SLE) and [day 2](https://www.youtube.com/watch?v=0ckOUBiuxVY) streams are available online. In this post, we’ll summarize the talks and announcements from the event.
## Day 1[Link for Day 1]()
[*Watch the full day 1 stream here.*](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=973s)
To kick off day 1, Meta CTO [Andrew “Boz” Bosworth](https://www.threads.net/@boztank) shared a welcome message followed by an introduction by [Seth Webster](https://twitter.com/sethwebster), who manages the React Org at Meta, and our MC [Ashley Narcisse](https://twitter.com/_darkfadr).
In the day 1 keynote, [Joe Savona](https://twitter.com/en_JS) shared our goals and vision for React to make it easy for anyone to build great user experiences. [Lauren Tan](https://twitter.com/potetotes) followed with a State of React, where she shared that React was downloaded over 1 billion times in 2023, and that 37% of new developers learn to program with React. Finally, she highlighted the work of the React community to make React, React.
For more, check out these talks from the community later in the conference:
- [Vanilla React](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=5542s) by [Ryan Florence](https://twitter.com/ryanflorence)
- [React Rhythm & Blues](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=12728s) by [Lee Robinson](https://twitter.com/leeerob)
- [RedwoodJS, now with React Server Components](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=26815s) by [Amy Dutton](https://twitter.com/selfteachme)
- [Introducing Universal React Server Components in Expo Router](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=20765s) by [Evan Bacon](https://twitter.com/Baconbrix)
Next in the keynote, [Josh Story](https://twitter.com/joshcstory) and [Andrew Clark](https://twitter.com/acdlite) shared new features coming in React 19, and announced the React 19 RC which is ready for testing in production. Check out all the features in the [React 19 release post](https://react.dev/blog/2024/12/05/react-19), and see these talks for deep dives on the new features:
- [What’s new in React 19](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=8880s) by [Lydia Hallie](https://twitter.com/lydiahallie)
- [React Unpacked: A Roadmap to React 19](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=10112s) by [Sam Selikoff](https://twitter.com/samselikoff)
- [React 19 Deep Dive: Coordinating HTML](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=24916s) by [Josh Story](https://twitter.com/joshcstory)
- [Enhancing Forms with React Server Components](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=25280s) by [Aurora Walberg Scharff](https://twitter.com/aurorascharff)
- [React for Two Computers](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=18825s) by [Dan Abramov](https://twitter.com/dan_abramov2)
- [And Now You Understand React Server Components](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=11256s) by [Kent C. Dodds](https://twitter.com/kentcdodds)
Finally, we ended the keynote with [Joe Savona](https://twitter.com/en_JS), [Sathya Gunasekaran](https://twitter.com/_gsathya), and [Mofei Zhang](https://twitter.com/zmofei) announcing that the React Compiler is now [Open Source](https://github.com/facebook/react/pull/29061), and sharing an experimental version of the React Compiler to try out.
For more information on using the Compiler and how it works, check out [the docs](https://react.dev/learn/react-compiler) and these talks:
- [Forget About Memo](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=12020s) by [Lauren Tan](https://twitter.com/potetotes)
- [React Compiler Deep Dive](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=9313s) by [Sathya Gunasekaran](https://twitter.com/_gsathya) and [Mofei Zhang](https://twitter.com/zmofei)
Watch the full day 1 keynote here:
## Day 2[Link for Day 2]()
[*Watch the full day 2 stream here.*](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=1720s)
To kick off day 2, [Seth Webster](https://twitter.com/sethwebster) shared a welcome message, followed by a Thank You from [Eli White](https://x.com/Eli_White) and an introduction by our Chief Vibes Officer [Ashley Narcisse](https://twitter.com/_darkfadr).
In the day 2 keynote, [Nicola Corti](https://twitter.com/cortinico) shared the State of React Native, including 78 million downloads in 2023. He also highlighted apps using React Native including 2000+ screens used inside of Meta; the product details page in Facebook Marketplace, which is visited more than 2 billion times per day; and part of the Microsoft Windows Start Menu and some features in almost every Microsoft Office product across mobile and desktop.
Nicola also highlighted all the work the community does to support React Native including libraries, frameworks, and multiple platforms. For more, check out these talks from the community:
- [Extending React Native beyond Mobile and Desktop Apps](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=5798s) by [Chris Traganos](https://twitter.com/chris_trag) and [Anisha Malde](https://twitter.com/anisha_malde)
- [Spatial computing with React](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=22525s) by [Michał Pierzchała](https://twitter.com/thymikee)
[Riccardo Cipolleschi](https://twitter.com/cipolleschir) continued the day 2 keynote by announcing that the React Native New Architecture is now in Beta and ready for apps to adopt in production. He shared new features and improvements in the new architecture, and shared the roadmap for the future of React Native. For more check out:
- [Cross Platform React](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=26569s) by [Olga Zinoveva](https://github.com/SlyCaptainFlint) and [Naman Goel](https://twitter.com/naman34)
Next in the keynote, Nicola announced that we are now recommending starting with a framework like Expo for all new apps created with React Native. With the change, he also announced a new React Native homepage and new Getting Started docs. You can view the new Getting Started guide in the [React Native docs](https://reactnative.dev/docs/next/environment-setup).
Finally, to end the keynote, [Kadi Kraman](https://twitter.com/kadikraman) shared the latest features and improvements in Expo, and how to get started developing with React Native using Expo.
Watch the full day 2 keynote here:
## Q&A[Link for Q&A]()
The React and React Native teams also ended each day with a Q&A session:
- [React Q&A](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=27518s) hosted by [Michael Chan](https://twitter.com/chantastic)
- [React Native Q&A](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=27935s) hosted by [Jamon Holmgren](https://twitter.com/jamonholmgren)
## And more…[Link for And more…]()
We also heard talks on accessibility, error reporting, css, and more:
- [Demystifying accessibility in React apps](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=20655s) by [Kateryna Porshnieva](https://twitter.com/krambertech)
- [Pigment CSS, CSS in the server component age](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=21696s) by [Olivier Tassinari](https://twitter.com/olivtassinari)
- [Real-time React Server Components](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=24070s) by [Sunil Pai](https://twitter.com/threepointone)
- [Let’s break React Rules](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=25862s) by [Charlotte Isambert](https://twitter.com/c_isambert)
- [Solve 100% of your errors](https://www.youtube.com/watch?v=0ckOUBiuxVY&t=19881s) by [Ryan Albrecht](https://github.com/ryan953)
## Thank you[Link for Thank you]()
Thank you to all the staff, speakers, and participants who made React Conf 2024 possible. There are too many to list, but we want to thank a few in particular.
Thank you to [Barbara Markiewicz](https://twitter.com/barbara_markie), the team at [Callstack](https://www.callstack.com/), and our React Team Developer Advocate [Matt Carroll](https://twitter.com/mattcarrollcode) for helping to plan the entire event; and to [Sunny Leggett](https://zeroslopeevents.com/about) and everyone from [Zero Slope](https://zeroslopeevents.com) for helping to organize the event.
Thank you [Ashley Narcisse](https://twitter.com/_darkfadr) for being our MC and Chief Vibes Officer; and to [Michael Chan](https://twitter.com/chantastic) and [Jamon Holmgren](https://twitter.com/jamonholmgren) for hosting the Q&A sessions.
Thank you [Seth Webster](https://twitter.com/sethwebster) and [Eli White](https://x.com/Eli_White) for welcoming us each day and providing direction on structure and content; and to [Tom Occhino](https://twitter.com/tomocchino) for joining us with a special message during the after-party.
Thank you [Ricky Hanlon](https://www.youtube.com/watch?v=FxTZL2U-uKg&t=1263s) for providing detailed feedback on talks, working on slide designs, and generally filling in the gaps to sweat the details.
Thank you [Callstack](https://www.callstack.com/) for building the conference website; and to [Kadi Kraman](https://twitter.com/kadikraman) and the [Expo](https://expo.dev/) team for building the conference mobile app.
Thank you to all the sponsors who made the event possible: [Remix](https://remix.run/), [Amazon](https://developer.amazon.com/apps-and-games?cmp=US_2024_05_3P_React-Conf-2024&ch=prtnr&chlast=prtnr&pub=ref&publast=ref&type=org&typelast=org), [MUI](https://mui.com/), [Sentry](https://sentry.io/for/react/?utm_source=sponsored-conf&utm_medium=sponsored-event&utm_campaign=frontend-fy25q2-evergreen&utm_content=logo-reactconf2024-learnmore), [Abbott](https://www.jobs.abbott/software), [Expo](https://expo.dev/), [RedwoodJS](https://redwoodjs.com/), and [Vercel](https://vercel.com).
Thank you to the AV Team for the visuals, stage, and sound; and to the Westin Hotel for hosting us.
Thank you to all the speakers who shared their knowledge and experiences with the community.
Finally, thank you to everyone who attended in person and online to show what makes React, React. React is more than a library, it is a community, and it was inspiring to see everyone come together to share and learn together.
See you next time!
[PreviousReact Compiler Beta Release and Roadmap](https://react.dev/blog/2024/10/21/react-compiler-beta-release)
[NextReact 19 RC](https://react.dev/blog/2024/04/25/react-19) |
https://react.dev/blog/2024/10/21/react-compiler-beta-release | [Blog](https://react.dev/blog)
# React Compiler Beta Release[Link for this heading]()
October 21, 2024 by [Lauren Tan](https://twitter.com/potetotes).
* * *
The React team is excited to share new updates:
1. We’re publishing React Compiler Beta today, so that early adopters and library maintainers can try it and provide feedback.
2. We’re officially supporting React Compiler for apps on React 17+, through an optional `react-compiler-runtime` package.
3. We’re opening up public membership of the [React Compiler Working Group](https://github.com/reactwg/react-compiler) to prepare the community for gradual adoption of the compiler.
* * *
At [React Conf 2024](https://react.dev/blog/2024/05/22/react-conf-2024-recap), we announced the experimental release of React Compiler, a build-time tool that optimizes your React app through automatic memoization. [You can find an introduction to React Compiler here](https://react.dev/learn/react-compiler).
Since the first release, we’ve fixed numerous bugs reported by the React community, received several high quality bug fixes and contributions[1]() to the compiler, made the compiler more resilient to the broad diversity of JavaScript patterns, and have continued to roll out the compiler more widely at Meta.
In this post, we want to share what’s next for React Compiler.
## Try React Compiler Beta today[Link for Try React Compiler Beta today]()
At [React India 2024](https://www.youtube.com/watch?v=qd5yk2gxbtg), we shared an update on React Compiler. Today, we are excited to announce a new Beta release of React Compiler and ESLint plugin. New betas are published to npm using the `@beta` tag.
To install React Compiler Beta:
Terminal
Copy
npm install -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta
Or, if you’re using Yarn:
Terminal
Copy
yarn add -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta
You can watch [Sathya Gunasekaran’s](https://twitter.com/_gsathya) talk at React India here:
## We recommend everyone use the React Compiler linter today[Link for We recommend everyone use the React Compiler linter today]()
React Compiler’s ESLint plugin helps developers proactively identify and correct [Rules of React](https://react.dev/reference/rules) violations. **We strongly recommend everyone use the linter today**. The linter does not require that you have the compiler installed, so you can use it independently, even if you are not ready to try out the compiler.
To install the linter only:
Terminal
Copy
npm install -D eslint-plugin-react-compiler@beta
Or, if you’re using Yarn:
Terminal
Copy
yarn add -D eslint-plugin-react-compiler@beta
After installation you can enable the linter by [adding it to your ESLint config](https://react.dev/learn/react-compiler). Using the linter helps identify Rules of React breakages, making it easier to adopt the compiler when it’s fully released.
## Backwards Compatibility[Link for Backwards Compatibility]()
React Compiler produces code that depends on runtime APIs added in React 19, but we’ve since added support for the compiler to also work with React 17 and 18. If you are not on React 19 yet, in the Beta release you can now try out React Compiler by specifying a minimum `target` in your compiler config, and adding `react-compiler-runtime` as a dependency. [You can find docs on this here](https://react.dev/learn/react-compiler).
## Using React Compiler in libraries[Link for Using React Compiler in libraries]()
Our initial release was focused on identifying major issues with using the compiler in applications. We’ve gotten great feedback and have substantially improved the compiler since then. We’re now ready for broad feedback from the community, and for library authors to try out the compiler to improve performance and the developer experience of maintaining your library.
React Compiler can also be used to compile libraries. Because React Compiler needs to run on the original source code prior to any code transformations, it is not possible for an application’s build pipeline to compile the libraries they use. Hence, our recommendation is for library maintainers to independently compile and test their libraries with the compiler, and ship compiled code to npm.
Because your code is pre-compiled, users of your library will not need to have the compiler enabled in order to benefit from the automatic memoization applied to your library. If your library targets apps not yet on React 19, specify a minimum `target` and add `react-compiler-runtime` as a direct dependency. The runtime package will use the correct implementation of APIs depending on the application’s version, and polyfill the missing APIs if necessary.
[You can find more docs on this here.](https://react.dev/learn/react-compiler)
## Opening up React Compiler Working Group to everyone[Link for Opening up React Compiler Working Group to everyone]()
We previously announced the invite-only [React Compiler Working Group](https://github.com/reactwg/react-compiler) at React Conf to provide feedback, ask questions, and collaborate on the compiler’s experimental release.
From today, together with the Beta release of React Compiler, we are opening up Working Group membership to everyone. The goal of the React Compiler Working Group is to prepare the ecosystem for a smooth, gradual adoption of React Compiler by existing applications and libraries. Please continue to file bug reports in the [React repo](https://github.com/facebook/react), but please leave feedback, ask questions, or share ideas in the [Working Group discussion forum](https://github.com/reactwg/react-compiler/discussions).
The core team will also use the discussions repo to share our research findings. As the Stable Release gets closer, any important information will also be posted on this forum.
## React Compiler at Meta[Link for React Compiler at Meta]()
At [React Conf](https://react.dev/blog/2024/05/22/react-conf-2024-recap), we shared that our rollout of the compiler on Quest Store and Instagram were successful. Since then, we’ve deployed React Compiler across several more major web apps at Meta, including [Facebook](https://www.facebook.com) and [Threads](https://www.threads.net). That means if you’ve used any of these apps recently, you may have had your experience powered by the compiler. We were able to onboard these apps onto the compiler with few code changes required, in a monorepo with more than 100,000 React components.
We’ve seen notable performance improvements across all of these apps. As we’ve rolled out, we’re continuing to see results on the order of [the wins we shared previously at ReactConf](https://youtu.be/lyEKhv8-3n0?t=3223). These apps have already been heavily hand tuned and optimized by Meta engineers and React experts over the years, so even improvements on the order of a few percent are a huge win for us.
We also expected developer productivity wins from React Compiler. To measure this, we collaborated with our data science partners at Meta[2]() to conduct a thorough statistical analysis of the impact of manual memoization on productivity. Before rolling out the compiler at Meta, we discovered that only about 8% of React pull requests used manual memoization and that these pull requests took 31-46% longer to author[3](). This confirmed our intuition that manual memoization introduces cognitive overhead, and we anticipate that React Compiler will lead to more efficient code authoring and review. Notably, React Compiler also ensures that *all* code is memoized by default, not just the (in our case) 8% where developers explicitly apply memoization.
## Roadmap to Stable[Link for Roadmap to Stable]()
*This is not a final roadmap, and is subject to change.*
We intend to ship a Release Candidate of the compiler in the near future following the Beta release, when the majority of apps and libraries that follow the Rules of React have been proven to work well with the compiler. After a period of final feedback from the community, we plan on a Stable Release for the compiler. The Stable Release will mark the beginning of a new foundation for React, and all apps and libraries will be strongly recommended to use the compiler and ESLint plugin.
- ✅ Experimental: Released at React Conf 2024, primarily for feedback from early adopters.
- ✅ Public Beta: Available today, for feedback from the wider community.
- 🚧 Release Candidate (RC): React Compiler works for the majority of rule-following apps and libraries without issue.
- 🚧 General Availability: After final feedback period from the community.
These releases also include the compiler’s ESLint plugin, which surfaces diagnostics statically analyzed by the compiler. We plan to combine the existing eslint-plugin-react-hooks plugin with the compiler’s ESLint plugin, so only one plugin needs to be installed.
Post-Stable, we plan to add more compiler optimizations and improvements. This includes both continual improvements to automatic memoization, and new optimizations altogether, with minimal to no change of product code. Upgrading to each new release of the compiler is aimed to be straightforward, and each upgrade will continue to improve performance and add better handling of diverse JavaScript and React patterns.
Throughout this process, we also plan to prototype an IDE extension for React. It is still very early in research, so we expect to be able to share more of our findings with you in a future React Labs blog post.
* * *
Thanks to [Sathya Gunasekaran](https://twitter.com/_gsathya), [Joe Savona](https://twitter.com/en_JS), [Ricky Hanlon](https://twitter.com/rickhanlonii), [Alex Taylor](https://github.com/alexmckenley), [Jason Bonta](https://twitter.com/someextent), and [Eli White](https://twitter.com/Eli_White) for reviewing and editing this post.
* * *
## Footnotes[Link for Footnotes]()
1. Thanks [@nikeee](https://github.com/facebook/react/pulls?q=is%3Apr%20author%3Anikeee), [@henryqdineen](https://github.com/facebook/react/pulls?q=is%3Apr%20author%3Ahenryqdineen), [@TrickyPi](https://github.com/facebook/react/pulls?q=is%3Apr%20author%3ATrickyPi), and several others for their contributions to the compiler. [↩]()
2. Thanks [Vaishali Garg](https://www.linkedin.com/in/vaishaligarg09) for leading this study on React Compiler at Meta, and for reviewing this post. [↩]()
3. After controlling on author tenure, diff length/complexity, and other potential confounding factors. [↩]()
[PreviousReact 19](https://react.dev/blog/2024/12/05/react-19)
[NextReact Conf 2024 Recap](https://react.dev/blog/2024/05/22/react-conf-2024-recap) |
https://react.dev/blog/2024/12/05/react-19 | [Blog](https://react.dev/blog)
# React v19[Link for this heading]()
December 05, 2024 by [The React Team](https://react.dev/community/team)
* * *
### Note
### React 19 is now stable\![Link for React 19 is now stable!]()
Additions since this post was originally shared with the React 19 RC in April:
- **Pre-warming for suspended trees**: see [Improvements to Suspense](https://react.dev/blog/2024/04/25/react-19-upgrade-guide).
- **React DOM static APIs**: see [New React DOM Static APIs]().
*The date for this post has been updated to reflect the stable release date.*
React v19 is now available on npm!
In our [React 19 Upgrade Guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide), we shared step-by-step instructions for upgrading your app to React 19. In this post, we’ll give an overview of the new features in React 19, and how you can adopt them.
- [What’s new in React 19]()
- [Improvements in React 19]()
- [How to upgrade]()
For a list of breaking changes, see the [Upgrade Guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide).
* * *
## What’s new in React 19[Link for What’s new in React 19]()
### Actions[Link for Actions]()
A common use case in React apps is to perform a data mutation and then update state in response. For example, when a user submits a form to change their name, you will make an API request, and then handle the response. In the past, you would need to handle pending states, errors, optimistic updates, and sequential requests manually.
For example, you could handle the pending and error state in `useState`:
```
// Before Actions
function UpdateName({}) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const handleSubmit = async () => {
setIsPending(true);
const error = await updateName(name);
setIsPending(false);
if (error) {
setError(error);
return;
}
redirect("/path");
};
return (
<div>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}
```
In React 19, we’re adding support for using async functions in transitions to handle pending states, errors, forms, and optimistic updates automatically.
For example, you can use `useTransition` to handle the pending state for you:
```
// Using pending state from Actions
function UpdateName({}) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const handleSubmit = () => {
startTransition(async () => {
const error = await updateName(name);
if (error) {
setError(error);
return;
}
redirect("/path");
})
};
return (
<div>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}
```
The async transition will immediately set the `isPending` state to true, make the async request(s), and switch `isPending` to false after any transitions. This allows you to keep the current UI responsive and interactive while the data is changing.
### Note
#### By convention, functions that use async transitions are called “Actions”.[Link for By convention, functions that use async transitions are called “Actions”.]()
Actions automatically manage submitting data for you:
- **Pending state**: Actions provide a pending state that starts at the beginning of a request and automatically resets when the final state update is committed.
- **Optimistic updates**: Actions support the new [`useOptimistic`]() hook so you can show users instant feedback while the requests are submitting.
- **Error handling**: Actions provide error handling so you can display Error Boundaries when a request fails, and revert optimistic updates to their original value automatically.
- **Forms**: `<form>` elements now support passing functions to the `action` and `formAction` props. Passing functions to the `action` props use Actions by default and reset the form automatically after submission.
Building on top of Actions, React 19 introduces [`useOptimistic`]() to manage optimistic updates, and a new hook [`React.useActionState`]() to handle common cases for Actions. In `react-dom` we’re adding [`<form>` Actions]() to manage forms automatically and [`useFormStatus`]() to support the common cases for Actions in forms.
In React 19, the above example can be simplified to:
```
// Using <form> Actions and useActionState
function ChangeName({ name, setName }) {
const [error, submitAction, isPending] = useActionState(
async (previousState, formData) => {
const error = await updateName(formData.get("name"));
if (error) {
return error;
}
redirect("/path");
return null;
},
null,
);
return (
<form action={submitAction}>
<input type="text" name="name" />
<button type="submit" disabled={isPending}>Update</button>
{error && <p>{error}</p>}
</form>
);
}
```
In the next section, we’ll break down each of the new Action features in React 19.
### New hook: `useActionState`[Link for this heading]()
To make the common cases easier for Actions, we’ve added a new hook called `useActionState`:
```
const [error, submitAction, isPending] = useActionState(
async (previousState, newName) => {
const error = await updateName(newName);
if (error) {
// You can return any result of the action.
// Here, we return only the error.
return error;
}
// handle success
return null;
},
null,
);
```
`useActionState` accepts a function (the “Action”), and returns a wrapped Action to call. This works because Actions compose. When the wrapped Action is called, `useActionState` will return the last result of the Action as `data`, and the pending state of the Action as `pending`.
### Note
`React.useActionState` was previously called `ReactDOM.useFormState` in the Canary releases, but we’ve renamed it and deprecated `useFormState`.
See [#28491](https://github.com/facebook/react/pull/28491) for more info.
For more information, see the docs for [`useActionState`](https://react.dev/reference/react/useActionState).
### React DOM: `<form>` Actions[Link for this heading]()
Actions are also integrated with React 19’s new `<form>` features for `react-dom`. We’ve added support for passing functions as the `action` and `formAction` props of `<form>`, `<input>`, and `<button>` elements to automatically submit forms with Actions:
```
<form action={actionFunction}>
```
When a `<form>` Action succeeds, React will automatically reset the form for uncontrolled components. If you need to reset the `<form>` manually, you can call the new `requestFormReset` React DOM API.
For more information, see the `react-dom` docs for [`<form>`](https://react.dev/reference/react-dom/components/form), [`<input>`](https://react.dev/reference/react-dom/components/input), and `<button>`.
### React DOM: New hook: `useFormStatus`[Link for this heading]()
In design systems, it’s common to write design components that need access to information about the `<form>` they’re in, without drilling props down to the component. This can be done via Context, but to make the common case easier, we’ve added a new hook `useFormStatus`:
```
import {useFormStatus} from 'react-dom';
function DesignButton() {
const {pending} = useFormStatus();
return <button type="submit" disabled={pending} />
}
```
`useFormStatus` reads the status of the parent `<form>` as if the form was a Context provider.
For more information, see the `react-dom` docs for [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus).
### New hook: `useOptimistic`[Link for this heading]()
Another common UI pattern when performing a data mutation is to show the final state optimistically while the async request is underway. In React 19, we’re adding a new hook called `useOptimistic` to make this easier:
```
function ChangeName({currentName, onUpdateName}) {
const [optimisticName, setOptimisticName] = useOptimistic(currentName);
const submitAction = async formData => {
const newName = formData.get("name");
setOptimisticName(newName);
const updatedName = await updateName(newName);
onUpdateName(updatedName);
};
return (
<form action={submitAction}>
<p>Your name is: {optimisticName}</p>
<p>
<label>Change Name:</label>
<input
type="text"
name="name"
disabled={currentName !== optimisticName}
/>
</p>
</form>
);
}
```
The `useOptimistic` hook will immediately render the `optimisticName` while the `updateName` request is in progress. When the update finishes or errors, React will automatically switch back to the `currentName` value.
For more information, see the docs for [`useOptimistic`](https://react.dev/reference/react/useOptimistic).
### New API: `use`[Link for this heading]()
In React 19 we’re introducing a new API to read resources in render: `use`.
For example, you can read a promise with `use`, and React will Suspend until the promise resolves:
```
import {use} from 'react';
function Comments({commentsPromise}) {
// `use` will suspend until the promise resolves.
const comments = use(commentsPromise);
return comments.map(comment => <p key={comment.id}>{comment}</p>);
}
function Page({commentsPromise}) {
// When `use` suspends in Comments,
// this Suspense boundary will be shown.
return (
<Suspense fallback={<div>Loading...</div>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
)
}
```
### Note
#### `use` does not support promises created in render.[Link for this heading]()
If you try to pass a promise created in render to `use`, React will warn:
Console
A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework.
To fix, you need to pass a promise from a suspense powered library or framework that supports caching for promises. In the future we plan to ship features to make it easier to cache promises in render.
You can also read context with `use`, allowing you to read Context conditionally such as after early returns:
```
import {use} from 'react';
import ThemeContext from './ThemeContext'
function Heading({children}) {
if (children == null) {
return null;
}
// This would not work with useContext
// because of the early return.
const theme = use(ThemeContext);
return (
<h1 style={{color: theme.color}}>
{children}
</h1>
);
}
```
The `use` API can only be called in render, similar to hooks. Unlike hooks, `use` can be called conditionally. In the future we plan to support more ways to consume resources in render with `use`.
For more information, see the docs for [`use`](https://react.dev/reference/react/use).
## New React DOM Static APIs[Link for New React DOM Static APIs]()
We’ve added two new APIs to `react-dom/static` for static site generation:
- [`prerender`](https://react.dev/reference/react-dom/static/prerender)
- [`prerenderToNodeStream`](https://react.dev/reference/react-dom/static/prerenderToNodeStream)
These new APIs improve on `renderToString` by waiting for data to load for static HTML generation. They are designed to work with streaming environments like Node.js Streams and Web Streams. For example, in a Web Stream environment, you can prerender a React tree to static HTML with `prerender`:
```
import { prerender } from 'react-dom/static';
async function handler(request) {
const {prelude} = await prerender(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(prelude, {
headers: { 'content-type': 'text/html' },
});
}
```
Prerender APIs will wait for all data to load before returning the static HTML stream. Streams can be converted to strings, or sent with a streaming response. They do not support streaming content as it loads, which is supported by the existing [React DOM server rendering APIs](https://react.dev/reference/react-dom/server).
For more information, see [React DOM Static APIs](https://react.dev/reference/react-dom/static).
## React Server Components[Link for React Server Components]()
### Server Components[Link for Server Components]()
Server Components are a new option that allows rendering components ahead of time, before bundling, in an environment separate from your client application or SSR server. This separate environment is the “server” in React Server Components. Server Components can run once at build time on your CI server, or they can be run for each request using a web server.
React 19 includes all of the React Server Components features included from the Canary channel. This means libraries that ship with Server Components can now target React 19 as a peer dependency with a `react-server` [export condition](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md) for use in frameworks that support the [Full-stack React Architecture](https://react.dev/learn/start-a-new-react-project).
### Note
#### How do I build support for Server Components?[Link for How do I build support for Server Components?]()
While React Server Components in React 19 are stable and will not break between minor versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x.
To support React Server Components as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement React Server Components in the future.
For more, see the docs for [React Server Components](https://react.dev/reference/rsc/server-components).
### Server Actions[Link for Server Actions]()
Server Actions allow Client Components to call async functions executed on the server.
When a Server Action is defined with the `"use server"` directive, your framework will automatically create a reference to the server function, and pass that reference to the Client Component. When that function is called on the client, React will send a request to the server to execute the function, and return the result.
### Note
#### There is no directive for Server Components.[Link for There is no directive for Server Components.]()
A common misunderstanding is that Server Components are denoted by `"use server"`, but there is no directive for Server Components. The `"use server"` directive is used for Server Actions.
For more info, see the docs for [Directives](https://react.dev/reference/rsc/directives).
Server Actions can be created in Server Components and passed as props to Client Components, or they can be imported and used in Client Components.
For more, see the docs for [React Server Actions](https://react.dev/reference/rsc/server-actions).
## Improvements in React 19[Link for Improvements in React 19]()
### `ref` as a prop[Link for this heading]()
Starting in React 19, you can now access `ref` as a prop for function components:
```
function MyInput({placeholder, ref}) {
return <input placeholder={placeholder} ref={ref} />
}
//...
<MyInput ref={ref} />
```
New function components will no longer need `forwardRef`, and we will be publishing a codemod to automatically update your components to use the new `ref` prop. In future versions we will deprecate and remove `forwardRef`.
### Note
`refs` passed to classes are not passed as props since they reference the component instance.
### Diffs for hydration errors[Link for Diffs for hydration errors]()
We also improved error reporting for hydration errors in `react-dom`. For example, instead of logging multiple errors in DEV without any information about the mismatch:
Console
Warning: Text content did not match. Server: “Server” Client: “Client” at span at App
Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.
Warning: Text content did not match. Server: “Server” Client: “Client” at span at App
Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.
Uncaught Error: Text content does not match server-rendered HTML. at checkForUnmatchedText …
We now log a single message with a diff of the mismatch:
Console
Uncaught Error: Hydration failed because the server rendered HTML didn’t match the client. As a result this tree will be regenerated on the client. This can happen if an SSR-ed Client Component used: - A server/client branch `if (typeof window !== 'undefined')`. - Variable input such as `Date.now()` or `Math.random()` which changes each time it’s called. - Date formatting in a user’s locale which doesn’t match the server. - External changing data without sending a snapshot of it along with the HTML. - Invalid HTML tag nesting. It can also happen if the client has a browser extension installed which messes with the HTML before React loaded. [https://react.dev/link/hydration-mismatch](https://react.dev/link/hydration-mismatch) <App> <span> + Client - Server at throwOnHydrationMismatch …
### `<Context>` as a provider[Link for this heading]()
In React 19, you can render `<Context>` as a provider instead of `<Context.Provider>`:
```
const ThemeContext = createContext('');
function App({children}) {
return (
<ThemeContext value="dark">
{children}
</ThemeContext>
);
}
```
New Context providers can use `<Context>` and we will be publishing a codemod to convert existing providers. In future versions we will deprecate `<Context.Provider>`.
### Cleanup functions for refs[Link for Cleanup functions for refs]()
We now support returning a cleanup function from `ref` callbacks:
```
<input
ref={(ref) => {
// ref created
// NEW: return a cleanup function to reset
// the ref when element is removed from DOM.
return () => {
// ref cleanup
};
}}
/>
```
When the component unmounts, React will call the cleanup function returned from the `ref` callback. This works for DOM refs, refs to class components, and `useImperativeHandle`.
### Note
Previously, React would call `ref` functions with `null` when unmounting the component. If your `ref` returns a cleanup function, React will now skip this step.
In future versions, we will deprecate calling refs with `null` when unmounting components.
Due to the introduction of ref cleanup functions, returning anything else from a `ref` callback will now be rejected by TypeScript. The fix is usually to stop using implicit returns, for example:
```
- <div ref={current => (instance = current)} />
+ <div ref={current => {instance = current}} />
```
The original code returned the instance of the `HTMLDivElement` and TypeScript wouldn’t know if this was *supposed* to be a cleanup function or if you didn’t want to return a cleanup function.
You can codemod this pattern with [`no-implicit-ref-callback-return`](https://github.com/eps1lon/types-react-codemod/).
### `useDeferredValue` initial value[Link for this heading]()
We’ve added an `initialValue` option to `useDeferredValue`:
```
function Search({deferredValue}) {
// On initial render the value is ''.
// Then a re-render is scheduled with the deferredValue.
const value = useDeferredValue(deferredValue, '');
return (
<Results query={value} />
);
}
```
When initialValue is provided, `useDeferredValue` will return it as `value` for the initial render of the component, and schedules a re-render in the background with the deferredValue returned.
For more, see [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue).
### Support for Document Metadata[Link for Support for Document Metadata]()
In HTML, document metadata tags like `<title>`, `<link>`, and `<meta>` are reserved for placement in the `<head>` section of the document. In React, the component that decides what metadata is appropriate for the app may be very far from the place where you render the `<head>` or React does not render the `<head>` at all. In the past, these elements would need to be inserted manually in an effect, or by libraries like [`react-helmet`](https://github.com/nfl/react-helmet), and required careful handling when server rendering a React application.
In React 19, we’re adding support for rendering document metadata tags in components natively:
```
function BlogPost({post}) {
return (
<article>
<h1>{post.title}</h1>
<title>{post.title}</title>
<meta name="author" content="Josh" />
<link rel="author" href="https://twitter.com/joshcstory/" />
<meta name="keywords" content={post.keywords} />
<p>
Eee equals em-see-squared...
</p>
</article>
);
}
```
When React renders this component, it will see the `<title>` `<link>` and `<meta>` tags, and automatically hoist them to the `<head>` section of document. By supporting these metadata tags natively, we’re able to ensure they work with client-only apps, streaming SSR, and Server Components.
### Note
#### You may still want a Metadata library[Link for You may still want a Metadata library]()
For simple use cases, rendering Document Metadata as tags may be suitable, but libraries can offer more powerful features like overriding generic metadata with specific metadata based on the current route. These features make it easier for frameworks and libraries like [`react-helmet`](https://github.com/nfl/react-helmet) to support metadata tags, rather than replace them.
For more info, see the docs for [`<title>`](https://react.dev/reference/react-dom/components/title), [`<link>`](https://react.dev/reference/react-dom/components/link), and [`<meta>`](https://react.dev/reference/react-dom/components/meta).
### Support for stylesheets[Link for Support for stylesheets]()
Stylesheets, both externally linked (`<link rel="stylesheet" href="...">`) and inline (`<style>...</style>`), require careful positioning in the DOM due to style precedence rules. Building a stylesheet capability that allows for composability within components is hard, so users often end up either loading all of their styles far from the components that may depend on them, or they use a style library which encapsulates this complexity.
In React 19, we’re addressing this complexity and providing even deeper integration into Concurrent Rendering on the Client and Streaming Rendering on the Server with built in support for stylesheets. If you tell React the `precedence` of your stylesheet it will manage the insertion order of the stylesheet in the DOM and ensure that the stylesheet (if external) is loaded before revealing content that depends on those style rules.
```
function ComponentOne() {
return (
<Suspense fallback="loading...">
<link rel="stylesheet" href="foo" precedence="default" />
<link rel="stylesheet" href="bar" precedence="high" />
<article class="foo-class bar-class">
{...}
</article>
</Suspense>
)
}
function ComponentTwo() {
return (
<div>
<p>{...}</p>
<link rel="stylesheet" href="baz" precedence="default" /> <-- will be inserted between foo & bar
</div>
)
}
```
During Server Side Rendering React will include the stylesheet in the `<head>`, which ensures that the browser will not paint until it has loaded. If the stylesheet is discovered late after we’ve already started streaming, React will ensure that the stylesheet is inserted into the `<head>` on the client before revealing the content of a Suspense boundary that depends on that stylesheet.
During Client Side Rendering React will wait for newly rendered stylesheets to load before committing the render. If you render this component from multiple places within your application React will only include the stylesheet once in the document:
```
function App() {
return <>
<ComponentOne />
...
<ComponentOne /> // won't lead to a duplicate stylesheet link in the DOM
</>
}
```
For users accustomed to loading stylesheets manually this is an opportunity to locate those stylesheets alongside the components that depend on them allowing for better local reasoning and an easier time ensuring you only load the stylesheets that you actually depend on.
Style libraries and style integrations with bundlers can also adopt this new capability so even if you don’t directly render your own stylesheets, you can still benefit as your tools are upgraded to use this feature.
For more details, read the docs for [`<link>`](https://react.dev/reference/react-dom/components/link) and [`<style>`](https://react.dev/reference/react-dom/components/style).
### Support for async scripts[Link for Support for async scripts]()
In HTML normal scripts (`<script src="...">`) and deferred scripts (`<script defer="" src="...">`) load in document order which makes rendering these kinds of scripts deep within your component tree challenging. Async scripts (`<script async="" src="...">`) however will load in arbitrary order.
In React 19 we’ve included better support for async scripts by allowing you to render them anywhere in your component tree, inside the components that actually depend on the script, without having to manage relocating and deduplicating script instances.
```
function MyComponent() {
return (
<div>
<script async={true} src="..." />
Hello World
</div>
)
}
function App() {
<html>
<body>
<MyComponent>
...
<MyComponent> // won't lead to duplicate script in the DOM
</body>
</html>
}
```
In all rendering environments, async scripts will be deduplicated so that React will only load and execute the script once even if it is rendered by multiple different components.
In Server Side Rendering, async scripts will be included in the `<head>` and prioritized behind more critical resources that block paint such as stylesheets, fonts, and image preloads.
For more details, read the docs for [`<script>`](https://react.dev/reference/react-dom/components/script).
### Support for preloading resources[Link for Support for preloading resources]()
During initial document load and on client side updates, telling the Browser about resources that it will likely need to load as early as possible can have a dramatic effect on page performance.
React 19 includes a number of new APIs for loading and preloading Browser resources to make it as easy as possible to build great experiences that aren’t held back by inefficient resource loading.
```
import { prefetchDNS, preconnect, preload, preinit } from 'react-dom'
function MyComponent() {
preinit('https://.../path/to/some/script.js', {as: 'script' }) // loads and executes this script eagerly
preload('https://.../path/to/font.woff', { as: 'font' }) // preloads this font
preload('https://.../path/to/stylesheet.css', { as: 'style' }) // preloads this stylesheet
prefetchDNS('https://...') // when you may not actually request anything from this host
preconnect('https://...') // when you will request something but aren't sure what
}
```
```
<!-- the above would result in the following DOM/HTML -->
<html>
<head>
<!-- links/scripts are prioritized by their utility to early loading, not call order -->
<link rel="prefetch-dns" href="https://...">
<link rel="preconnect" href="https://...">
<link rel="preload" as="font" href="https://.../path/to/font.woff">
<link rel="preload" as="style" href="https://.../path/to/stylesheet.css">
<script async="" src="https://.../path/to/some/script.js"></script>
</head>
<body>
...
</body>
</html>
```
These APIs can be used to optimize initial page loads by moving discovery of additional resources like fonts out of stylesheet loading. They can also make client updates faster by prefetching a list of resources used by an anticipated navigation and then eagerly preloading those resources on click or even on hover.
For more details see [Resource Preloading APIs](https://react.dev/reference/react-dom).
### Compatibility with third-party scripts and extensions[Link for Compatibility with third-party scripts and extensions]()
We’ve improved hydration to account for third-party scripts and browser extensions.
When hydrating, if an element that renders on the client doesn’t match the element found in the HTML from the server, React will force a client re-render to fix up the content. Previously, if an element was inserted by third-party scripts or browser extensions, it would trigger a mismatch error and client render.
In React 19, unexpected tags in the `<head>` and `<body>` will be skipped over, avoiding the mismatch errors. If React needs to re-render the entire document due to an unrelated hydration mismatch, it will leave in place stylesheets inserted by third-party scripts and browser extensions.
### Better error reporting[Link for Better error reporting]()
We improved error handling in React 19 to remove duplication and provide options for handling caught and uncaught errors. For example, when there’s an error in render caught by an Error Boundary, previously React would throw the error twice (once for the original error, then again after failing to automatically recover), and then call `console.error` with info about where the error occurred.
This resulted in three errors for every caught error:
Console
Uncaught Error: hit at Throws at renderWithHooks …
Uncaught Error: hit <-- Duplicate at Throws at renderWithHooks …
The above error occurred in the Throws component: at Throws at ErrorBoundary at App React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
In React 19, we log a single error with all the error information included:
Console
Error: hit at Throws at renderWithHooks … The above error occurred in the Throws component: at Throws at ErrorBoundary at App React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary. at ErrorBoundary at App
Additionally, we’ve added two new root options to complement `onRecoverableError`:
- `onCaughtError`: called when React catches an error in an Error Boundary.
- `onUncaughtError`: called when an error is thrown and not caught by an Error Boundary.
- `onRecoverableError`: called when an error is thrown and automatically recovered.
For more info and examples, see the docs for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot).
### Support for Custom Elements[Link for Support for Custom Elements]()
React 19 adds full support for custom elements and passes all tests on [Custom Elements Everywhere](https://custom-elements-everywhere.com/).
In past versions, using Custom Elements in React has been difficult because React treated unrecognized props as attributes rather than properties. In React 19, we’ve added support for properties that works on the client and during SSR with the following strategy:
- **Server Side Rendering**: props passed to a custom element will render as attributes if their type is a primitive value like `string`, `number`, or the value is `true`. Props with non-primitive types like `object`, `symbol`, `function`, or value `false` will be omitted.
- **Client Side Rendering**: props that match a property on the Custom Element instance will be assigned as properties, otherwise they will be assigned as attributes.
Thanks to [Joey Arhar](https://github.com/josepharhar) for driving the design and implementation of Custom Element support in React.
#### How to upgrade[Link for How to upgrade]()
See the [React 19 Upgrade Guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide) for step-by-step instructions and a full list of breaking and notable changes.
*Note: this post was originally published 04/25/2024 and has been updated to 12/05/2024 with the stable release.*
[PreviousBlog](https://react.dev/blog)
[NextReact Compiler Beta Release and Roadmap](https://react.dev/blog/2024/10/21/react-compiler-beta-release) |
https://react.dev/learn/installation | [Learn React](https://react.dev/learn)
# Installation[Link for this heading]()
React has been designed from the start for gradual adoption. You can use as little or as much React as you need. Whether you want to get a taste of React, add some interactivity to an HTML page, or start a complex React-powered app, this section will help you get started.
### In this chapter
- [How to start a new React project](https://react.dev/learn/start-a-new-react-project)
- [How to add React to an existing project](https://react.dev/learn/add-react-to-an-existing-project)
- [How to set up your editor](https://react.dev/learn/editor-setup)
- [How to install React Developer Tools](https://react.dev/learn/react-developer-tools)
## Try React[Link for Try React]()
You don’t need to install anything to play with React. Try editing this sandbox!
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
export default function App() {
return <Greeting name="world" />
}
```
You can edit it directly or open it in a new tab by pressing the “Fork” button in the upper right corner.
Most pages in the React documentation contain sandboxes like this. Outside of the React documentation, there are many online sandboxes that support React: for example, [CodeSandbox](https://codesandbox.io/s/new), [StackBlitz](https://stackblitz.com/fork/react), or [CodePen.](https://codepen.io/pen?template=QWYVwWN)
### Try React locally[Link for Try React locally]()
To try React locally on your computer, [download this HTML page.](https://gist.githubusercontent.com/gaearon/0275b1e1518599bbeafcde4722e79ed1/raw/db72dcbf3384ee1708c4a07d3be79860db04bff0/example.html) Open it in your editor and in your browser!
## Start a new React project[Link for Start a new React project]()
If you want to build an app or a website fully with React, [start a new React project.](https://react.dev/learn/start-a-new-react-project)
## Add React to an existing project[Link for Add React to an existing project]()
If want to try using React in your existing app or a website, [add React to an existing project.](https://react.dev/learn/add-react-to-an-existing-project)
## Next steps[Link for Next steps]()
Head to the [Quick Start](https://react.dev/learn) guide for a tour of the most important React concepts you will encounter every day.
[PreviousThinking in React](https://react.dev/learn/thinking-in-react)
[NextStart a New React Project](https://react.dev/learn/start-a-new-react-project) |
https://react.dev/learn/adding-interactivity | [Learn React](https://react.dev/learn)
# Adding Interactivity[Link for this heading]()
Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called *state.* You can add state to any component, and update it as needed. In this chapter, you’ll learn how to write components that handle interactions, update their state, and display different output over time.
### In this chapter
- [How to handle user-initiated events](https://react.dev/learn/responding-to-events)
- [How to make components “remember” information with state](https://react.dev/learn/state-a-components-memory)
- [How React updates the UI in two phases](https://react.dev/learn/render-and-commit)
- [Why state doesn’t update right after you change it](https://react.dev/learn/state-as-a-snapshot)
- [How to queue multiple state updates](https://react.dev/learn/queueing-a-series-of-state-updates)
- [How to update an object in state](https://react.dev/learn/updating-objects-in-state)
- [How to update an array in state](https://react.dev/learn/updating-arrays-in-state)
## Responding to events[Link for Responding to events]()
React lets you add *event handlers* to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
Built-in components like `<button>` only support built-in browser events like `onClick`. However, you can also create your own components, and give their event handler props any application-specific names that you like.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function App() {
return (
<Toolbar
onPlayMovie={() => alert('Playing!')}
onUploadImage={() => alert('Uploading!')}
/>
);
}
function Toolbar({ onPlayMovie, onUploadImage }) {
return (
<div>
<Button onClick={onPlayMovie}>
Play Movie
</Button>
<Button onClick={onUploadImage}>
Upload Image
</Button>
</div>
);
}
function Button({ onClick, children }) {
return (
<button onClick={onClick}>
{children}
</button>
);
}
```
Show more
## Ready to learn this topic?
Read [**Responding to Events**](https://react.dev/learn/responding-to-events) to learn how to add event handlers.
[Read More](https://react.dev/learn/responding-to-events)
* * *
## State: a component’s memory[Link for State: a component’s memory]()
Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” puts a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state.*
You can add state to a component with a [`useState`](https://react.dev/reference/react/useState) Hook. *Hooks* are special functions that let your components use React features (state is one of those features). The `useState` Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
```
const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);
```
Here is how an image gallery uses and updates state on click:
App.jsdata.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
import { sculptureList } from './data.js';
export default function Gallery() {
const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);
const hasNext = index < sculptureList.length - 1;
function handleNextClick() {
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}
function handleMoreClick() {
setShowMore(!showMore);
}
let sculpture = sculptureList[index];
return (
<>
<button onClick={handleNextClick}>
Next
</button>
<h2>
<i>{sculpture.name} </i>
by {sculpture.artist}
</h2>
<h3>
({index + 1} of {sculptureList.length})
</h3>
<button onClick={handleMoreClick}>
{showMore ? 'Hide' : 'Show'} details
</button>
{showMore && <p>{sculpture.description}</p>}
<img
src={sculpture.url}
alt={sculpture.alt}
/>
</>
);
}
```
Show more
## Ready to learn this topic?
Read [**State: A Component’s Memory**](https://react.dev/learn/state-a-components-memory) to learn how to remember a value and update it on interaction.
[Read More](https://react.dev/learn/state-a-components-memory)
* * *
## Render and commit[Link for Render and commit]()
Before your components are displayed on the screen, they must be rendered by React. Understanding the steps in this process will help you think about how your code executes and explain its behavior.
Imagine that your components are cooks in the kitchen, assembling tasty dishes from ingredients. In this scenario, React is the waiter who puts in requests from customers and brings them their orders. This process of requesting and serving UI has three steps:
1. **Triggering** a render (delivering the diner’s order to the kitchen)
2. **Rendering** the component (preparing the order in the kitchen)
3. **Committing** to the DOM (placing the order on the table)
<!--THE END-->
1. ![React as a server in a restaurant, fetching orders from the users and delivering them to the Component Kitchen.](/images/docs/illustrations/i_render-and-commit1.png)
Trigger
2. ![The Card Chef gives React a fresh Card component.](/images/docs/illustrations/i_render-and-commit2.png)
Render
3. ![React delivers the Card to the user at their table.](/images/docs/illustrations/i_render-and-commit3.png)
Commit
Illustrated by [Rachel Lee Nabors](https://nearestnabors.com/)
## Ready to learn this topic?
Read [**Render and Commit**](https://react.dev/learn/render-and-commit) to learn the lifecycle of a UI update.
[Read More](https://react.dev/learn/render-and-commit)
* * *
## State as a snapshot[Link for State as a snapshot]()
Unlike regular JavaScript variables, React state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first!
```
console.log(count); // 0
setCount(count + 1); // Request a re-render with 1
console.log(count); // Still 0!
```
This behavior helps you avoid subtle bugs. Here is a little chat app. Try to guess what happens if you press “Send” first and *then* change the recipient to Bob. Whose name will appear in the `alert` five seconds later?
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Form() {
const [to, setTo] = useState('Alice');
const [message, setMessage] = useState('Hello');
function handleSubmit(e) {
e.preventDefault();
setTimeout(() => {
alert(`You said ${message} to ${to}`);
}, 5000);
}
return (
<form onSubmit={handleSubmit}>
<label>
To:{' '}
<select
value={to}
onChange={e => setTo(e.target.value)}>
<option value="Alice">Alice</option>
<option value="Bob">Bob</option>
</select>
</label>
<textarea
placeholder="Message"
value={message}
onChange={e => setMessage(e.target.value)}
/>
<button type="submit">Send</button>
</form>
);
}
```
Show more
## Ready to learn this topic?
Read [**State as a Snapshot**](https://react.dev/learn/state-as-a-snapshot) to learn why state appears “fixed” and unchanging inside the event handlers.
[Read More](https://react.dev/learn/state-as-a-snapshot)
* * *
## Queueing a series of state updates[Link for Queueing a series of state updates]()
This component is buggy: clicking “+3” increments the score only once.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Counter() {
const [score, setScore] = useState(0);
function increment() {
setScore(score + 1);
}
return (
<>
<button onClick={() => increment()}>+1</button>
<button onClick={() => {
increment();
increment();
increment();
}}>+3</button>
<h1>Score: {score}</h1>
</>
)
}
```
Show more
[State as a Snapshot](https://react.dev/learn/state-as-a-snapshot) explains why this is happening. Setting state requests a new re-render, but does not change it in the already running code. So `score` continues to be `0` right after you call `setScore(score + 1)`.
```
console.log(score); // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score); // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score); // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score); // 0
```
You can fix this by passing an *updater function* when setting state. Notice how replacing `setScore(score + 1)` with `setScore(s => s + 1)` fixes the “+3” button. This lets you queue multiple state updates.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Counter() {
const [score, setScore] = useState(0);
function increment() {
setScore(s => s + 1);
}
return (
<>
<button onClick={() => increment()}>+1</button>
<button onClick={() => {
increment();
increment();
increment();
}}>+3</button>
<h1>Score: {score}</h1>
</>
)
}
```
Show more
## Ready to learn this topic?
Read [**Queueing a Series of State Updates**](https://react.dev/learn/queueing-a-series-of-state-updates) to learn how to queue a sequence of state updates.
[Read More](https://react.dev/learn/queueing-a-series-of-state-updates)
* * *
## Updating objects in state[Link for Updating objects in state]()
State can hold any kind of JavaScript value, including objects. But you shouldn’t change objects and arrays that you hold in the React state directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy.
Usually, you will use the `...` spread syntax to copy objects and arrays that you want to change. For example, updating a nested object could look like this:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Form() {
const [person, setPerson] = useState({
name: 'Niki de Saint Phalle',
artwork: {
title: 'Blue Nana',
city: 'Hamburg',
image: 'https://i.imgur.com/Sd1AgUOm.jpg',
}
});
function handleNameChange(e) {
setPerson({
...person,
name: e.target.value
});
}
function handleTitleChange(e) {
setPerson({
...person,
artwork: {
...person.artwork,
title: e.target.value
}
});
}
function handleCityChange(e) {
setPerson({
...person,
artwork: {
...person.artwork,
city: e.target.value
}
});
}
function handleImageChange(e) {
setPerson({
...person,
artwork: {
...person.artwork,
image: e.target.value
}
});
}
return (
<>
<label>
Name:
<input
value={person.name}
onChange={handleNameChange}
/>
</label>
<label>
Title:
<input
value={person.artwork.title}
onChange={handleTitleChange}
/>
</label>
<label>
City:
<input
value={person.artwork.city}
onChange={handleCityChange}
/>
</label>
<label>
Image:
<input
value={person.artwork.image}
onChange={handleImageChange}
/>
</label>
<p>
<i>{person.artwork.title}</i>
{' by '}
{person.name}
<br />
(located in {person.artwork.city})
</p>
<img
src={person.artwork.image}
alt={person.artwork.title}
/>
</>
);
}
```
Show more
If copying objects in code gets tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer) to reduce repetitive code:
package.jsonApp.js
package.json
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
{
"dependencies": {
"immer": "1.7.3",
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest",
"use-immer": "0.5.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {}
}
```
## Ready to learn this topic?
Read [**Updating Objects in State**](https://react.dev/learn/updating-objects-in-state) to learn how to update objects correctly.
[Read More](https://react.dev/learn/updating-objects-in-state)
* * *
## Updating arrays in state[Link for Updating arrays in state]()
Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
const initialList = [
{ id: 0, title: 'Big Bellies', seen: false },
{ id: 1, title: 'Lunar Landscape', seen: false },
{ id: 2, title: 'Terracotta Army', seen: true },
];
export default function BucketList() {
const [list, setList] = useState(
initialList
);
function handleToggle(artworkId, nextSeen) {
setList(list.map(artwork => {
if (artwork.id === artworkId) {
return { ...artwork, seen: nextSeen };
} else {
return artwork;
}
}));
}
return (
<>
<h1>Art Bucket List</h1>
<h2>My list of art to see:</h2>
<ItemList
artworks={list}
onToggle={handleToggle} />
</>
);
}
function ItemList({ artworks, onToggle }) {
return (
<ul>
{artworks.map(artwork => (
<li key={artwork.id}>
<label>
<input
type="checkbox"
checked={artwork.seen}
onChange={e => {
onToggle(
artwork.id,
e.target.checked
);
}}
/>
{artwork.title}
</label>
</li>
))}
</ul>
);
}
```
Show more
If copying arrays in code gets tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer) to reduce repetitive code:
package.jsonApp.js
package.json
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
{
"dependencies": {
"immer": "1.7.3",
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest",
"use-immer": "0.5.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {}
}
```
## Ready to learn this topic?
Read [**Updating Arrays in State**](https://react.dev/learn/updating-arrays-in-state) to learn how to update arrays correctly.
[Read More](https://react.dev/learn/updating-arrays-in-state)
* * *
## What’s next?[Link for What’s next?]()
Head over to [Responding to Events](https://react.dev/learn/responding-to-events) to start reading this chapter page by page!
Or, if you’re already familiar with these topics, why not read about [Managing State](https://react.dev/learn/managing-state)?
[PreviousYour UI as a Tree](https://react.dev/learn/understanding-your-ui-as-a-tree)
[NextResponding to Events](https://react.dev/learn/responding-to-events) |
https://react.dev/learn/describing-the-ui | [Learn React](https://react.dev/learn)
# Describing the UI[Link for this heading]()
React is a JavaScript library for rendering user interfaces (UI). UI is built from small units like buttons, text, and images. React lets you combine them into reusable, nestable *components.* From web sites to phone apps, everything on the screen can be broken down into components. In this chapter, you’ll learn to create, customize, and conditionally display React components.
### In this chapter
- [How to write your first React component](https://react.dev/learn/your-first-component)
- [When and how to create multi-component files](https://react.dev/learn/importing-and-exporting-components)
- [How to add markup to JavaScript with JSX](https://react.dev/learn/writing-markup-with-jsx)
- [How to use curly braces with JSX to access JavaScript functionality from your components](https://react.dev/learn/javascript-in-jsx-with-curly-braces)
- [How to configure components with props](https://react.dev/learn/passing-props-to-a-component)
- [How to conditionally render components](https://react.dev/learn/conditional-rendering)
- [How to render multiple components at a time](https://react.dev/learn/rendering-lists)
- [How to avoid confusing bugs by keeping components pure](https://react.dev/learn/keeping-components-pure)
- [Why understanding your UI as trees is useful](https://react.dev/learn/understanding-your-ui-as-a-tree)
## Your first component[Link for Your first component]()
React applications are built from isolated pieces of UI called *components*. A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a `Gallery` component rendering three `Profile` components:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
function Profile() {
return (
<img
src="https://i.imgur.com/MK3eW3As.jpg"
alt="Katherine Johnson"
/>
);
}
export default function Gallery() {
return (
<section>
<h1>Amazing scientists</h1>
<Profile />
<Profile />
<Profile />
</section>
);
}
```
Show more
## Ready to learn this topic?
Read [**Your First Component**](https://react.dev/learn/your-first-component) to learn how to declare and use React components.
[Read More](https://react.dev/learn/your-first-component)
* * *
## Importing and exporting components[Link for Importing and exporting components]()
You can declare many components in one file, but large files can get difficult to navigate. To solve this, you can *export* a component into its own file, and then *import* that component from another file:
Gallery.jsProfile.js
Gallery.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import Profile from './Profile.js';
export default function Gallery() {
return (
<section>
<h1>Amazing scientists</h1>
<Profile />
<Profile />
<Profile />
</section>
);
}
```
## Ready to learn this topic?
Read [**Importing and Exporting Components**](https://react.dev/learn/importing-and-exporting-components) to learn how to split components into their own files.
[Read More](https://react.dev/learn/importing-and-exporting-components)
* * *
## Writing markup with JSX[Link for Writing markup with JSX]()
Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information.
If we paste existing HTML markup into a React component, it won’t always work:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function TodoList() {
return (
// This doesn't quite work!
<h1>Hedy Lamarr's Todos</h1>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
class="photo"
>
<ul>
<li>Invent new traffic lights
<li>Rehearse a movie scene
<li>Improve spectrum technology
</ul>
```
Show more
If you have existing HTML like this, you can fix it using a [converter](https://transform.tools/html-to-jsx):
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function TodoList() {
return (
<>
<h1>Hedy Lamarr's Todos</h1>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
className="photo"
/>
<ul>
<li>Invent new traffic lights</li>
<li>Rehearse a movie scene</li>
<li>Improve spectrum technology</li>
</ul>
</>
);
}
```
Show more
## Ready to learn this topic?
Read [**Writing Markup with JSX**](https://react.dev/learn/writing-markup-with-jsx) to learn how to write valid JSX.
[Read More](https://react.dev/learn/writing-markup-with-jsx)
* * *
## JavaScript in JSX with curly braces[Link for JavaScript in JSX with curly braces]()
JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to “open a window” to JavaScript:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
const person = {
name: 'Gregorio Y. Zara',
theme: {
backgroundColor: 'black',
color: 'pink'
}
};
export default function TodoList() {
return (
<div style={person.theme}>
<h1>{person.name}'s Todos</h1>
<img
className="avatar"
src="https://i.imgur.com/7vQD0fPs.jpg"
alt="Gregorio Y. Zara"
/>
<ul>
<li>Improve the videophone</li>
<li>Prepare aeronautics lectures</li>
<li>Work on the alcohol-fuelled engine</li>
</ul>
</div>
);
}
```
Show more
## Ready to learn this topic?
Read [**JavaScript in JSX with Curly Braces**](https://react.dev/learn/javascript-in-jsx-with-curly-braces) to learn how to access JavaScript data from JSX.
[Read More](https://react.dev/learn/javascript-in-jsx-with-curly-braces)
* * *
## Passing props to a component[Link for Passing props to a component]()
React components use *props* to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, functions, and even JSX!
App.jsutils.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { getImageUrl } from './utils.js'
export default function Profile() {
return (
<Card>
<Avatar
size={100}
person={{
name: 'Katsuko Saruhashi',
imageId: 'YfeOqp2'
}}
/>
</Card>
);
}
function Avatar({ person, size }) {
return (
<img
className="avatar"
src={getImageUrl(person)}
alt={person.name}
width={size}
height={size}
/>
);
}
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
```
Show more
## Ready to learn this topic?
Read [**Passing Props to a Component**](https://react.dev/learn/passing-props-to-a-component) to learn how to pass and read props.
[Read More](https://react.dev/learn/passing-props-to-a-component)
* * *
## Conditional rendering[Link for Conditional rendering]()
Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like `if` statements, `&&`, and `? :` operators.
In this example, the JavaScript `&&` operator is used to conditionally render a checkmark:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked && '✅'}
</li>
);
}
export default function PackingList() {
return (
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item
isPacked={true}
name="Space suit"
/>
<Item
isPacked={true}
name="Helmet with a golden leaf"
/>
<Item
isPacked={false}
name="Photo of Tam"
/>
</ul>
</section>
);
}
```
Show more
## Ready to learn this topic?
Read [**Conditional Rendering**](https://react.dev/learn/conditional-rendering) to learn the different ways to render content conditionally.
[Read More](https://react.dev/learn/conditional-rendering)
* * *
## Rendering lists[Link for Rendering lists]()
You will often want to display multiple similar components from a collection of data. You can use JavaScript’s `filter()` and `map()` with React to filter and transform your array of data into an array of components.
For each array item, you will need to specify a `key`. Usually, you will want to use an ID from the database as a `key`. Keys let React keep track of each item’s place in the list even if the list changes.
App.jsdata.jsutils.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { people } from './data.js';
import { getImageUrl } from './utils.js';
export default function List() {
const listItems = people.map(person =>
<li key={person.id}>
<img
src={getImageUrl(person)}
alt={person.name}
/>
<p>
<b>{person.name}:</b>
{' ' + person.profession + ' '}
known for {person.accomplishment}
</p>
</li>
);
return (
<article>
<h1>Scientists</h1>
<ul>{listItems}</ul>
</article>
);
}
```
Show more
## Ready to learn this topic?
Read [**Rendering Lists**](https://react.dev/learn/rendering-lists) to learn how to render a list of components, and how to choose a key.
[Read More](https://react.dev/learn/rendering-lists)
* * *
## Keeping components pure[Link for Keeping components pure]()
Some JavaScript functions are *pure.* A pure function:
- **Minds its own business.** It does not change any objects or variables that existed before it was called.
- **Same inputs, same output.** Given the same inputs, a pure function should always return the same result.
By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. Here is an example of an impure component:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
let guest = 0;
function Cup() {
// Bad: changing a preexisting variable!
guest = guest + 1;
return <h2>Tea cup for guest #{guest}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
);
}
```
Show more
You can make this component pure by passing a prop instead of modifying a preexisting variable:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
function Cup({ guest }) {
return <h2>Tea cup for guest #{guest}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup guest={1} />
<Cup guest={2} />
<Cup guest={3} />
</>
);
}
```
## Ready to learn this topic?
Read [**Keeping Components Pure**](https://react.dev/learn/keeping-components-pure) to learn how to write components as pure, predictable functions.
[Read More](https://react.dev/learn/keeping-components-pure)
* * *
## Your UI as a tree[Link for Your UI as a tree]()
React uses trees to model the relationships between components and modules.
A React render tree is a representation of the parent and child relationship between components.
![A tree graph with five nodes, with each node representing a component. The root node is located at the top the tree graph and is labelled 'Root Component'. It has two arrows extending down to two nodes labelled 'Component A' and 'Component C'. Each of the arrows is labelled with 'renders'. 'Component A' has a single 'renders' arrow to a node labelled 'Component B'. 'Component C' has a single 'renders' arrow to a node labelled 'Component D'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fgeneric_render_tree.dark.png&w=1080&q=75)
![A tree graph with five nodes, with each node representing a component. The root node is located at the top the tree graph and is labelled 'Root Component'. It has two arrows extending down to two nodes labelled 'Component A' and 'Component C'. Each of the arrows is labelled with 'renders'. 'Component A' has a single 'renders' arrow to a node labelled 'Component B'. 'Component C' has a single 'renders' arrow to a node labelled 'Component D'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fgeneric_render_tree.png&w=1080&q=75)
An example React render tree.
Components near the top of the tree, near the root component, are considered top-level components. Components with no child components are leaf components. This categorization of components is useful for understanding data flow and rendering performance.
Modelling the relationship between JavaScript modules is another useful way to understand your app. We refer to it as a module dependency tree.
![A tree graph with five nodes. Each node represents a JavaScript module. The top-most node is labelled 'RootModule.js'. It has three arrows extending to the nodes: 'ModuleA.js', 'ModuleB.js', and 'ModuleC.js'. Each arrow is labelled as 'imports'. 'ModuleC.js' node has a single 'imports' arrow that points to a node labelled 'ModuleD.js'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fgeneric_dependency_tree.dark.png&w=1080&q=75)
![A tree graph with five nodes. Each node represents a JavaScript module. The top-most node is labelled 'RootModule.js'. It has three arrows extending to the nodes: 'ModuleA.js', 'ModuleB.js', and 'ModuleC.js'. Each arrow is labelled as 'imports'. 'ModuleC.js' node has a single 'imports' arrow that points to a node labelled 'ModuleD.js'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fgeneric_dependency_tree.png&w=1080&q=75)
An example module dependency tree.
A dependency tree is often used by build tools to bundle all the relevant JavaScript code for the client to download and render. A large bundle size regresses user experience for React apps. Understanding the module dependency tree is helpful to debug such issues.
## Ready to learn this topic?
Read [**Your UI as a Tree**](https://react.dev/learn/understanding-your-ui-as-a-tree) to learn how to create a render and module dependency trees for a React app and how they’re useful mental models for improving user experience and performance.
[Read More](https://react.dev/learn/understanding-your-ui-as-a-tree)
* * *
## What’s next?[Link for What’s next?]()
Head over to [Your First Component](https://react.dev/learn/your-first-component) to start reading this chapter page by page!
Or, if you’re already familiar with these topics, why not read about [Adding Interactivity](https://react.dev/learn/adding-interactivity)?
[NextYour First Component](https://react.dev/learn/your-first-component) |
https://react.dev/learn/managing-state | [Learn React](https://react.dev/learn)
# Managing State[Link for this heading]()
Intermediate
As your application grows, it helps to be more intentional about how your state is organized and how the data flows between your components. Redundant or duplicate state is a common source of bugs. In this chapter, you’ll learn how to structure your state well, how to keep your state update logic maintainable, and how to share state between distant components.
### In this chapter
- [How to think about UI changes as state changes](https://react.dev/learn/reacting-to-input-with-state)
- [How to structure state well](https://react.dev/learn/choosing-the-state-structure)
- [How to “lift state up” to share it between components](https://react.dev/learn/sharing-state-between-components)
- [How to control whether the state gets preserved or reset](https://react.dev/learn/preserving-and-resetting-state)
- [How to consolidate complex state logic in a function](https://react.dev/learn/extracting-state-logic-into-a-reducer)
- [How to pass information without “prop drilling”](https://react.dev/learn/passing-data-deeply-with-context)
- [How to scale state management as your app grows](https://react.dev/learn/scaling-up-with-reducer-and-context)
## Reacting to input with state[Link for Reacting to input with state]()
With React, you won’t modify the UI from code directly. For example, you won’t write commands like “disable the button”, “enable the button”, “show the success message”, etc. Instead, you will describe the UI you want to see for the different visual states of your component (“initial state”, “typing state”, “success state”), and then trigger the state changes in response to user input. This is similar to how designers think about UI.
Here is a quiz form built using React. Note how it uses the `status` state variable to determine whether to enable or disable the submit button, and whether to show the success message instead.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Form() {
const [answer, setAnswer] = useState('');
const [error, setError] = useState(null);
const [status, setStatus] = useState('typing');
if (status === 'success') {
return <h1>That's right!</h1>
}
async function handleSubmit(e) {
e.preventDefault();
setStatus('submitting');
try {
await submitForm(answer);
setStatus('success');
} catch (err) {
setStatus('typing');
setError(err);
}
}
function handleTextareaChange(e) {
setAnswer(e.target.value);
}
return (
<>
<h2>City quiz</h2>
<p>
In which city is there a billboard that turns air into drinkable water?
</p>
<form onSubmit={handleSubmit}>
<textarea
value={answer}
onChange={handleTextareaChange}
disabled={status === 'submitting'}
/>
<br />
<button disabled={
answer.length === 0 ||
status === 'submitting'
}>
Submit
</button>
{error !== null &&
<p className="Error">
{error.message}
</p>
}
</form>
</>
);
}
function submitForm(answer) {
// Pretend it's hitting the network.
return new Promise((resolve, reject) => {
setTimeout(() => {
let shouldError = answer.toLowerCase() !== 'lima'
if (shouldError) {
reject(new Error('Good guess but a wrong answer. Try again!'));
} else {
resolve();
}
}, 1500);
});
}
```
Show more
## Ready to learn this topic?
Read [**Reacting to Input with State**](https://react.dev/learn/reacting-to-input-with-state) to learn how to approach interactions with a state-driven mindset.
[Read More](https://react.dev/learn/reacting-to-input-with-state)
* * *
## Choosing the state structure[Link for Choosing the state structure]()
Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. The most important principle is that state shouldn’t contain redundant or duplicated information. If there’s unnecessary state, it’s easy to forget to update it, and introduce bugs!
For example, this form has a **redundant** `fullName` state variable:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Form() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [fullName, setFullName] = useState('');
function handleFirstNameChange(e) {
setFirstName(e.target.value);
setFullName(e.target.value + ' ' + lastName);
}
function handleLastNameChange(e) {
setLastName(e.target.value);
setFullName(firstName + ' ' + e.target.value);
}
return (
<>
<h2>Let’s check you in</h2>
<label>
First name:{' '}
<input
value={firstName}
onChange={handleFirstNameChange}
/>
</label>
<label>
Last name:{' '}
<input
value={lastName}
onChange={handleLastNameChange}
/>
</label>
<p>
Your ticket will be issued to: <b>{fullName}</b>
</p>
</>
);
}
```
Show more
You can remove it and simplify the code by calculating `fullName` while the component is rendering:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Form() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const fullName = firstName + ' ' + lastName;
function handleFirstNameChange(e) {
setFirstName(e.target.value);
}
function handleLastNameChange(e) {
setLastName(e.target.value);
}
return (
<>
<h2>Let’s check you in</h2>
<label>
First name:{' '}
<input
value={firstName}
onChange={handleFirstNameChange}
/>
</label>
<label>
Last name:{' '}
<input
value={lastName}
onChange={handleLastNameChange}
/>
</label>
<p>
Your ticket will be issued to: <b>{fullName}</b>
</p>
</>
);
}
```
Show more
This might seem like a small change, but many bugs in React apps are fixed this way.
## Ready to learn this topic?
Read [**Choosing the State Structure**](https://react.dev/learn/choosing-the-state-structure) to learn how to design the state shape to avoid bugs.
[Read More](https://react.dev/learn/choosing-the-state-structure)
* * *
## Sharing state between components[Link for Sharing state between components]()
Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as “lifting state up”, and it’s one of the most common things you will do writing React code.
In this example, only one panel should be active at a time. To achieve this, instead of keeping the active state inside each individual panel, the parent component holds the state and specifies the props for its children.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Accordion() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<>
<h2>Almaty, Kazakhstan</h2>
<Panel
title="About"
isActive={activeIndex === 0}
onShow={() => setActiveIndex(0)}
>
With a population of about 2 million, Almaty is Kazakhstan's largest city. From 1929 to 1997, it was its capital city.
</Panel>
<Panel
title="Etymology"
isActive={activeIndex === 1}
onShow={() => setActiveIndex(1)}
>
The name comes from <span lang="kk-KZ">алма</span>, the Kazakh word for "apple" and is often translated as "full of apples". In fact, the region surrounding Almaty is thought to be the ancestral home of the apple, and the wild <i lang="la">Malus sieversii</i> is considered a likely candidate for the ancestor of the modern domestic apple.
</Panel>
</>
);
}
function Panel({
title,
children,
isActive,
onShow
}) {
return (
<section className="panel">
<h3>{title}</h3>
{isActive ? (
<p>{children}</p>
) : (
<button onClick={onShow}>
Show
</button>
)}
</section>
);
}
```
Show more
## Ready to learn this topic?
Read [**Sharing State Between Components**](https://react.dev/learn/sharing-state-between-components) to learn how to lift state up and keep components in sync.
[Read More](https://react.dev/learn/sharing-state-between-components)
* * *
## Preserving and resetting state[Link for Preserving and resetting state]()
When you re-render a component, React needs to decide which parts of the tree to keep (and update), and which parts to discard or re-create from scratch. In most cases, React’s automatic behavior works well enough. By default, React preserves the parts of the tree that “match up” with the previously rendered component tree.
However, sometimes this is not what you want. In this chat app, typing a message and then switching the recipient does not reset the input. This can make the user accidentally send a message to the wrong person:
App.jsContactList.jsChat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
import Chat from './Chat.js';
import ContactList from './ContactList.js';
export default function Messenger() {
const [to, setTo] = useState(contacts[0]);
return (
<div>
<ContactList
contacts={contacts}
selectedContact={to}
onSelect={contact => setTo(contact)}
/>
<Chat contact={to} />
</div>
)
}
const contacts = [
{ name: 'Taylor', email: '[email protected]' },
{ name: 'Alice', email: '[email protected]' },
{ name: 'Bob', email: '[email protected]' }
];
```
Show more
React lets you override the default behavior, and *force* a component to reset its state by passing it a different `key`, like `<Chat key={email} />`. This tells React that if the recipient is different, it should be considered a *different* `Chat` component that needs to be re-created from scratch with the new data (and UI like inputs). Now switching between the recipients resets the input field—even though you render the same component.
App.jsContactList.jsChat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
import Chat from './Chat.js';
import ContactList from './ContactList.js';
export default function Messenger() {
const [to, setTo] = useState(contacts[0]);
return (
<div>
<ContactList
contacts={contacts}
selectedContact={to}
onSelect={contact => setTo(contact)}
/>
<Chat key={to.email} contact={to} />
</div>
)
}
const contacts = [
{ name: 'Taylor', email: '[email protected]' },
{ name: 'Alice', email: '[email protected]' },
{ name: 'Bob', email: '[email protected]' }
];
```
Show more
## Ready to learn this topic?
Read [**Preserving and Resetting State**](https://react.dev/learn/preserving-and-resetting-state) to learn the lifetime of state and how to control it.
[Read More](https://react.dev/learn/preserving-and-resetting-state)
* * *
## Extracting state logic into a reducer[Link for Extracting state logic into a reducer]()
Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called “reducer”. Your event handlers become concise because they only specify the user “actions”. At the bottom of the file, the reducer function specifies how the state should update in response to each action!
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useReducer } from 'react';
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
export default function TaskApp() {
const [tasks, dispatch] = useReducer(
tasksReducer,
initialTasks
);
function handleAddTask(text) {
dispatch({
type: 'added',
id: nextId++,
text: text,
});
}
function handleChangeTask(task) {
dispatch({
type: 'changed',
task: task
});
}
function handleDeleteTask(taskId) {
dispatch({
type: 'deleted',
id: taskId
});
}
return (
<>
<h1>Prague itinerary</h1>
<AddTask
onAddTask={handleAddTask}
/>
<TaskList
tasks={tasks}
onChangeTask={handleChangeTask}
onDeleteTask={handleDeleteTask}
/>
</>
);
}
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added': {
return [...tasks, {
id: action.id,
text: action.text,
done: false
}];
}
case 'changed': {
return tasks.map(t => {
if (t.id === action.task.id) {
return action.task;
} else {
return t;
}
});
}
case 'deleted': {
return tasks.filter(t => t.id !== action.id);
}
default: {
throw Error('Unknown action: ' + action.type);
}
}
}
let nextId = 3;
const initialTasks = [
{ id: 0, text: 'Visit Kafka Museum', done: true },
{ id: 1, text: 'Watch a puppet show', done: false },
{ id: 2, text: 'Lennon Wall pic', done: false }
];
```
Show more
## Ready to learn this topic?
Read [**Extracting State Logic into a Reducer**](https://react.dev/learn/extracting-state-logic-into-a-reducer) to learn how to consolidate logic in the reducer function.
[Read More](https://react.dev/learn/extracting-state-logic-into-a-reducer)
* * *
## Passing data deeply with context[Link for Passing data deeply with context]()
Usually, you will pass information from a parent component to a child component via props. But passing props can become inconvenient if you need to pass some prop through many components, or if many components need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep it is—without passing it explicitly through props.
Here, the `Heading` component determines its heading level by “asking” the closest `Section` for its level. Each `Section` tracks its own level by asking the parent `Section` and adding one to it. Every `Section` provides information to all components below it without passing props—it does that through context.
App.jsSection.jsHeading.jsLevelContext.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import Heading from './Heading.js';
import Section from './Section.js';
export default function Page() {
return (
<Section>
<Heading>Title</Heading>
<Section>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Section>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Section>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
</Section>
</Section>
</Section>
</Section>
);
}
```
Show more
## Ready to learn this topic?
Read [**Passing Data Deeply with Context**](https://react.dev/learn/passing-data-deeply-with-context) to learn about using context as an alternative to passing props.
[Read More](https://react.dev/learn/passing-data-deeply-with-context)
* * *
## Scaling up with reducer and context[Link for Scaling up with reducer and context]()
Reducers let you consolidate a component’s state update logic. Context lets you pass information deep down to other components. You can combine reducers and context together to manage state of a complex screen.
With this approach, a parent component with complex state manages it with a reducer. Other components anywhere deep in the tree can read its state via context. They can also dispatch actions to update that state.
App.jsTasksContext.jsAddTask.jsTaskList.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
import { TasksProvider } from './TasksContext.js';
export default function TaskApp() {
return (
<TasksProvider>
<h1>Day off in Kyoto</h1>
<AddTask />
<TaskList />
</TasksProvider>
);
}
```
## Ready to learn this topic?
Read [**Scaling Up with Reducer and Context**](https://react.dev/learn/scaling-up-with-reducer-and-context) to learn how state management scales in a growing app.
[Read More](https://react.dev/learn/scaling-up-with-reducer-and-context)
* * *
## What’s next?[Link for What’s next?]()
Head over to [Reacting to Input with State](https://react.dev/learn/reacting-to-input-with-state) to start reading this chapter page by page!
Or, if you’re already familiar with these topics, why not read about [Escape Hatches](https://react.dev/learn/escape-hatches)?
[PreviousUpdating Arrays in State](https://react.dev/learn/updating-arrays-in-state)
[NextReacting to Input with State](https://react.dev/learn/reacting-to-input-with-state) |
https://react.dev/blog/2024/12/05/react-19 | [Blog](https://react.dev/blog)
# React v19[Link for this heading]()
December 05, 2024 by [The React Team](https://react.dev/community/team)
* * *
### Note
### React 19 is now stable\![Link for React 19 is now stable!]()
Additions since this post was originally shared with the React 19 RC in April:
- **Pre-warming for suspended trees**: see [Improvements to Suspense](https://react.dev/blog/2024/04/25/react-19-upgrade-guide).
- **React DOM static APIs**: see [New React DOM Static APIs]().
*The date for this post has been updated to reflect the stable release date.*
React v19 is now available on npm!
In our [React 19 Upgrade Guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide), we shared step-by-step instructions for upgrading your app to React 19. In this post, we’ll give an overview of the new features in React 19, and how you can adopt them.
- [What’s new in React 19]()
- [Improvements in React 19]()
- [How to upgrade]()
For a list of breaking changes, see the [Upgrade Guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide).
* * *
## What’s new in React 19[Link for What’s new in React 19]()
### Actions[Link for Actions]()
A common use case in React apps is to perform a data mutation and then update state in response. For example, when a user submits a form to change their name, you will make an API request, and then handle the response. In the past, you would need to handle pending states, errors, optimistic updates, and sequential requests manually.
For example, you could handle the pending and error state in `useState`:
```
// Before Actions
function UpdateName({}) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const handleSubmit = async () => {
setIsPending(true);
const error = await updateName(name);
setIsPending(false);
if (error) {
setError(error);
return;
}
redirect("/path");
};
return (
<div>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}
```
In React 19, we’re adding support for using async functions in transitions to handle pending states, errors, forms, and optimistic updates automatically.
For example, you can use `useTransition` to handle the pending state for you:
```
// Using pending state from Actions
function UpdateName({}) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const handleSubmit = () => {
startTransition(async () => {
const error = await updateName(name);
if (error) {
setError(error);
return;
}
redirect("/path");
})
};
return (
<div>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}
```
The async transition will immediately set the `isPending` state to true, make the async request(s), and switch `isPending` to false after any transitions. This allows you to keep the current UI responsive and interactive while the data is changing.
### Note
#### By convention, functions that use async transitions are called “Actions”.[Link for By convention, functions that use async transitions are called “Actions”.]()
Actions automatically manage submitting data for you:
- **Pending state**: Actions provide a pending state that starts at the beginning of a request and automatically resets when the final state update is committed.
- **Optimistic updates**: Actions support the new [`useOptimistic`]() hook so you can show users instant feedback while the requests are submitting.
- **Error handling**: Actions provide error handling so you can display Error Boundaries when a request fails, and revert optimistic updates to their original value automatically.
- **Forms**: `<form>` elements now support passing functions to the `action` and `formAction` props. Passing functions to the `action` props use Actions by default and reset the form automatically after submission.
Building on top of Actions, React 19 introduces [`useOptimistic`]() to manage optimistic updates, and a new hook [`React.useActionState`]() to handle common cases for Actions. In `react-dom` we’re adding [`<form>` Actions]() to manage forms automatically and [`useFormStatus`]() to support the common cases for Actions in forms.
In React 19, the above example can be simplified to:
```
// Using <form> Actions and useActionState
function ChangeName({ name, setName }) {
const [error, submitAction, isPending] = useActionState(
async (previousState, formData) => {
const error = await updateName(formData.get("name"));
if (error) {
return error;
}
redirect("/path");
return null;
},
null,
);
return (
<form action={submitAction}>
<input type="text" name="name" />
<button type="submit" disabled={isPending}>Update</button>
{error && <p>{error}</p>}
</form>
);
}
```
In the next section, we’ll break down each of the new Action features in React 19.
### New hook: `useActionState`[Link for this heading]()
To make the common cases easier for Actions, we’ve added a new hook called `useActionState`:
```
const [error, submitAction, isPending] = useActionState(
async (previousState, newName) => {
const error = await updateName(newName);
if (error) {
// You can return any result of the action.
// Here, we return only the error.
return error;
}
// handle success
return null;
},
null,
);
```
`useActionState` accepts a function (the “Action”), and returns a wrapped Action to call. This works because Actions compose. When the wrapped Action is called, `useActionState` will return the last result of the Action as `data`, and the pending state of the Action as `pending`.
### Note
`React.useActionState` was previously called `ReactDOM.useFormState` in the Canary releases, but we’ve renamed it and deprecated `useFormState`.
See [#28491](https://github.com/facebook/react/pull/28491) for more info.
For more information, see the docs for [`useActionState`](https://react.dev/reference/react/useActionState).
### React DOM: `<form>` Actions[Link for this heading]()
Actions are also integrated with React 19’s new `<form>` features for `react-dom`. We’ve added support for passing functions as the `action` and `formAction` props of `<form>`, `<input>`, and `<button>` elements to automatically submit forms with Actions:
```
<form action={actionFunction}>
```
When a `<form>` Action succeeds, React will automatically reset the form for uncontrolled components. If you need to reset the `<form>` manually, you can call the new `requestFormReset` React DOM API.
For more information, see the `react-dom` docs for [`<form>`](https://react.dev/reference/react-dom/components/form), [`<input>`](https://react.dev/reference/react-dom/components/input), and `<button>`.
### React DOM: New hook: `useFormStatus`[Link for this heading]()
In design systems, it’s common to write design components that need access to information about the `<form>` they’re in, without drilling props down to the component. This can be done via Context, but to make the common case easier, we’ve added a new hook `useFormStatus`:
```
import {useFormStatus} from 'react-dom';
function DesignButton() {
const {pending} = useFormStatus();
return <button type="submit" disabled={pending} />
}
```
`useFormStatus` reads the status of the parent `<form>` as if the form was a Context provider.
For more information, see the `react-dom` docs for [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus).
### New hook: `useOptimistic`[Link for this heading]()
Another common UI pattern when performing a data mutation is to show the final state optimistically while the async request is underway. In React 19, we’re adding a new hook called `useOptimistic` to make this easier:
```
function ChangeName({currentName, onUpdateName}) {
const [optimisticName, setOptimisticName] = useOptimistic(currentName);
const submitAction = async formData => {
const newName = formData.get("name");
setOptimisticName(newName);
const updatedName = await updateName(newName);
onUpdateName(updatedName);
};
return (
<form action={submitAction}>
<p>Your name is: {optimisticName}</p>
<p>
<label>Change Name:</label>
<input
type="text"
name="name"
disabled={currentName !== optimisticName}
/>
</p>
</form>
);
}
```
The `useOptimistic` hook will immediately render the `optimisticName` while the `updateName` request is in progress. When the update finishes or errors, React will automatically switch back to the `currentName` value.
For more information, see the docs for [`useOptimistic`](https://react.dev/reference/react/useOptimistic).
### New API: `use`[Link for this heading]()
In React 19 we’re introducing a new API to read resources in render: `use`.
For example, you can read a promise with `use`, and React will Suspend until the promise resolves:
```
import {use} from 'react';
function Comments({commentsPromise}) {
// `use` will suspend until the promise resolves.
const comments = use(commentsPromise);
return comments.map(comment => <p key={comment.id}>{comment}</p>);
}
function Page({commentsPromise}) {
// When `use` suspends in Comments,
// this Suspense boundary will be shown.
return (
<Suspense fallback={<div>Loading...</div>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
)
}
```
### Note
#### `use` does not support promises created in render.[Link for this heading]()
If you try to pass a promise created in render to `use`, React will warn:
Console
A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework.
To fix, you need to pass a promise from a suspense powered library or framework that supports caching for promises. In the future we plan to ship features to make it easier to cache promises in render.
You can also read context with `use`, allowing you to read Context conditionally such as after early returns:
```
import {use} from 'react';
import ThemeContext from './ThemeContext'
function Heading({children}) {
if (children == null) {
return null;
}
// This would not work with useContext
// because of the early return.
const theme = use(ThemeContext);
return (
<h1 style={{color: theme.color}}>
{children}
</h1>
);
}
```
The `use` API can only be called in render, similar to hooks. Unlike hooks, `use` can be called conditionally. In the future we plan to support more ways to consume resources in render with `use`.
For more information, see the docs for [`use`](https://react.dev/reference/react/use).
## New React DOM Static APIs[Link for New React DOM Static APIs]()
We’ve added two new APIs to `react-dom/static` for static site generation:
- [`prerender`](https://react.dev/reference/react-dom/static/prerender)
- [`prerenderToNodeStream`](https://react.dev/reference/react-dom/static/prerenderToNodeStream)
These new APIs improve on `renderToString` by waiting for data to load for static HTML generation. They are designed to work with streaming environments like Node.js Streams and Web Streams. For example, in a Web Stream environment, you can prerender a React tree to static HTML with `prerender`:
```
import { prerender } from 'react-dom/static';
async function handler(request) {
const {prelude} = await prerender(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(prelude, {
headers: { 'content-type': 'text/html' },
});
}
```
Prerender APIs will wait for all data to load before returning the static HTML stream. Streams can be converted to strings, or sent with a streaming response. They do not support streaming content as it loads, which is supported by the existing [React DOM server rendering APIs](https://react.dev/reference/react-dom/server).
For more information, see [React DOM Static APIs](https://react.dev/reference/react-dom/static).
## React Server Components[Link for React Server Components]()
### Server Components[Link for Server Components]()
Server Components are a new option that allows rendering components ahead of time, before bundling, in an environment separate from your client application or SSR server. This separate environment is the “server” in React Server Components. Server Components can run once at build time on your CI server, or they can be run for each request using a web server.
React 19 includes all of the React Server Components features included from the Canary channel. This means libraries that ship with Server Components can now target React 19 as a peer dependency with a `react-server` [export condition](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md) for use in frameworks that support the [Full-stack React Architecture](https://react.dev/learn/start-a-new-react-project).
### Note
#### How do I build support for Server Components?[Link for How do I build support for Server Components?]()
While React Server Components in React 19 are stable and will not break between minor versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x.
To support React Server Components as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement React Server Components in the future.
For more, see the docs for [React Server Components](https://react.dev/reference/rsc/server-components).
### Server Actions[Link for Server Actions]()
Server Actions allow Client Components to call async functions executed on the server.
When a Server Action is defined with the `"use server"` directive, your framework will automatically create a reference to the server function, and pass that reference to the Client Component. When that function is called on the client, React will send a request to the server to execute the function, and return the result.
### Note
#### There is no directive for Server Components.[Link for There is no directive for Server Components.]()
A common misunderstanding is that Server Components are denoted by `"use server"`, but there is no directive for Server Components. The `"use server"` directive is used for Server Actions.
For more info, see the docs for [Directives](https://react.dev/reference/rsc/directives).
Server Actions can be created in Server Components and passed as props to Client Components, or they can be imported and used in Client Components.
For more, see the docs for [React Server Actions](https://react.dev/reference/rsc/server-actions).
## Improvements in React 19[Link for Improvements in React 19]()
### `ref` as a prop[Link for this heading]()
Starting in React 19, you can now access `ref` as a prop for function components:
```
function MyInput({placeholder, ref}) {
return <input placeholder={placeholder} ref={ref} />
}
//...
<MyInput ref={ref} />
```
New function components will no longer need `forwardRef`, and we will be publishing a codemod to automatically update your components to use the new `ref` prop. In future versions we will deprecate and remove `forwardRef`.
### Note
`refs` passed to classes are not passed as props since they reference the component instance.
### Diffs for hydration errors[Link for Diffs for hydration errors]()
We also improved error reporting for hydration errors in `react-dom`. For example, instead of logging multiple errors in DEV without any information about the mismatch:
Console
Warning: Text content did not match. Server: “Server” Client: “Client” at span at App
Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.
Warning: Text content did not match. Server: “Server” Client: “Client” at span at App
Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.
Uncaught Error: Text content does not match server-rendered HTML. at checkForUnmatchedText …
We now log a single message with a diff of the mismatch:
Console
Uncaught Error: Hydration failed because the server rendered HTML didn’t match the client. As a result this tree will be regenerated on the client. This can happen if an SSR-ed Client Component used: - A server/client branch `if (typeof window !== 'undefined')`. - Variable input such as `Date.now()` or `Math.random()` which changes each time it’s called. - Date formatting in a user’s locale which doesn’t match the server. - External changing data without sending a snapshot of it along with the HTML. - Invalid HTML tag nesting. It can also happen if the client has a browser extension installed which messes with the HTML before React loaded. [https://react.dev/link/hydration-mismatch](https://react.dev/link/hydration-mismatch) <App> <span> + Client - Server at throwOnHydrationMismatch …
### `<Context>` as a provider[Link for this heading]()
In React 19, you can render `<Context>` as a provider instead of `<Context.Provider>`:
```
const ThemeContext = createContext('');
function App({children}) {
return (
<ThemeContext value="dark">
{children}
</ThemeContext>
);
}
```
New Context providers can use `<Context>` and we will be publishing a codemod to convert existing providers. In future versions we will deprecate `<Context.Provider>`.
### Cleanup functions for refs[Link for Cleanup functions for refs]()
We now support returning a cleanup function from `ref` callbacks:
```
<input
ref={(ref) => {
// ref created
// NEW: return a cleanup function to reset
// the ref when element is removed from DOM.
return () => {
// ref cleanup
};
}}
/>
```
When the component unmounts, React will call the cleanup function returned from the `ref` callback. This works for DOM refs, refs to class components, and `useImperativeHandle`.
### Note
Previously, React would call `ref` functions with `null` when unmounting the component. If your `ref` returns a cleanup function, React will now skip this step.
In future versions, we will deprecate calling refs with `null` when unmounting components.
Due to the introduction of ref cleanup functions, returning anything else from a `ref` callback will now be rejected by TypeScript. The fix is usually to stop using implicit returns, for example:
```
- <div ref={current => (instance = current)} />
+ <div ref={current => {instance = current}} />
```
The original code returned the instance of the `HTMLDivElement` and TypeScript wouldn’t know if this was *supposed* to be a cleanup function or if you didn’t want to return a cleanup function.
You can codemod this pattern with [`no-implicit-ref-callback-return`](https://github.com/eps1lon/types-react-codemod/).
### `useDeferredValue` initial value[Link for this heading]()
We’ve added an `initialValue` option to `useDeferredValue`:
```
function Search({deferredValue}) {
// On initial render the value is ''.
// Then a re-render is scheduled with the deferredValue.
const value = useDeferredValue(deferredValue, '');
return (
<Results query={value} />
);
}
```
When initialValue is provided, `useDeferredValue` will return it as `value` for the initial render of the component, and schedules a re-render in the background with the deferredValue returned.
For more, see [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue).
### Support for Document Metadata[Link for Support for Document Metadata]()
In HTML, document metadata tags like `<title>`, `<link>`, and `<meta>` are reserved for placement in the `<head>` section of the document. In React, the component that decides what metadata is appropriate for the app may be very far from the place where you render the `<head>` or React does not render the `<head>` at all. In the past, these elements would need to be inserted manually in an effect, or by libraries like [`react-helmet`](https://github.com/nfl/react-helmet), and required careful handling when server rendering a React application.
In React 19, we’re adding support for rendering document metadata tags in components natively:
```
function BlogPost({post}) {
return (
<article>
<h1>{post.title}</h1>
<title>{post.title}</title>
<meta name="author" content="Josh" />
<link rel="author" href="https://twitter.com/joshcstory/" />
<meta name="keywords" content={post.keywords} />
<p>
Eee equals em-see-squared...
</p>
</article>
);
}
```
When React renders this component, it will see the `<title>` `<link>` and `<meta>` tags, and automatically hoist them to the `<head>` section of document. By supporting these metadata tags natively, we’re able to ensure they work with client-only apps, streaming SSR, and Server Components.
### Note
#### You may still want a Metadata library[Link for You may still want a Metadata library]()
For simple use cases, rendering Document Metadata as tags may be suitable, but libraries can offer more powerful features like overriding generic metadata with specific metadata based on the current route. These features make it easier for frameworks and libraries like [`react-helmet`](https://github.com/nfl/react-helmet) to support metadata tags, rather than replace them.
For more info, see the docs for [`<title>`](https://react.dev/reference/react-dom/components/title), [`<link>`](https://react.dev/reference/react-dom/components/link), and [`<meta>`](https://react.dev/reference/react-dom/components/meta).
### Support for stylesheets[Link for Support for stylesheets]()
Stylesheets, both externally linked (`<link rel="stylesheet" href="...">`) and inline (`<style>...</style>`), require careful positioning in the DOM due to style precedence rules. Building a stylesheet capability that allows for composability within components is hard, so users often end up either loading all of their styles far from the components that may depend on them, or they use a style library which encapsulates this complexity.
In React 19, we’re addressing this complexity and providing even deeper integration into Concurrent Rendering on the Client and Streaming Rendering on the Server with built in support for stylesheets. If you tell React the `precedence` of your stylesheet it will manage the insertion order of the stylesheet in the DOM and ensure that the stylesheet (if external) is loaded before revealing content that depends on those style rules.
```
function ComponentOne() {
return (
<Suspense fallback="loading...">
<link rel="stylesheet" href="foo" precedence="default" />
<link rel="stylesheet" href="bar" precedence="high" />
<article class="foo-class bar-class">
{...}
</article>
</Suspense>
)
}
function ComponentTwo() {
return (
<div>
<p>{...}</p>
<link rel="stylesheet" href="baz" precedence="default" /> <-- will be inserted between foo & bar
</div>
)
}
```
During Server Side Rendering React will include the stylesheet in the `<head>`, which ensures that the browser will not paint until it has loaded. If the stylesheet is discovered late after we’ve already started streaming, React will ensure that the stylesheet is inserted into the `<head>` on the client before revealing the content of a Suspense boundary that depends on that stylesheet.
During Client Side Rendering React will wait for newly rendered stylesheets to load before committing the render. If you render this component from multiple places within your application React will only include the stylesheet once in the document:
```
function App() {
return <>
<ComponentOne />
...
<ComponentOne /> // won't lead to a duplicate stylesheet link in the DOM
</>
}
```
For users accustomed to loading stylesheets manually this is an opportunity to locate those stylesheets alongside the components that depend on them allowing for better local reasoning and an easier time ensuring you only load the stylesheets that you actually depend on.
Style libraries and style integrations with bundlers can also adopt this new capability so even if you don’t directly render your own stylesheets, you can still benefit as your tools are upgraded to use this feature.
For more details, read the docs for [`<link>`](https://react.dev/reference/react-dom/components/link) and [`<style>`](https://react.dev/reference/react-dom/components/style).
### Support for async scripts[Link for Support for async scripts]()
In HTML normal scripts (`<script src="...">`) and deferred scripts (`<script defer="" src="...">`) load in document order which makes rendering these kinds of scripts deep within your component tree challenging. Async scripts (`<script async="" src="...">`) however will load in arbitrary order.
In React 19 we’ve included better support for async scripts by allowing you to render them anywhere in your component tree, inside the components that actually depend on the script, without having to manage relocating and deduplicating script instances.
```
function MyComponent() {
return (
<div>
<script async={true} src="..." />
Hello World
</div>
)
}
function App() {
<html>
<body>
<MyComponent>
...
<MyComponent> // won't lead to duplicate script in the DOM
</body>
</html>
}
```
In all rendering environments, async scripts will be deduplicated so that React will only load and execute the script once even if it is rendered by multiple different components.
In Server Side Rendering, async scripts will be included in the `<head>` and prioritized behind more critical resources that block paint such as stylesheets, fonts, and image preloads.
For more details, read the docs for [`<script>`](https://react.dev/reference/react-dom/components/script).
### Support for preloading resources[Link for Support for preloading resources]()
During initial document load and on client side updates, telling the Browser about resources that it will likely need to load as early as possible can have a dramatic effect on page performance.
React 19 includes a number of new APIs for loading and preloading Browser resources to make it as easy as possible to build great experiences that aren’t held back by inefficient resource loading.
```
import { prefetchDNS, preconnect, preload, preinit } from 'react-dom'
function MyComponent() {
preinit('https://.../path/to/some/script.js', {as: 'script' }) // loads and executes this script eagerly
preload('https://.../path/to/font.woff', { as: 'font' }) // preloads this font
preload('https://.../path/to/stylesheet.css', { as: 'style' }) // preloads this stylesheet
prefetchDNS('https://...') // when you may not actually request anything from this host
preconnect('https://...') // when you will request something but aren't sure what
}
```
```
<!-- the above would result in the following DOM/HTML -->
<html>
<head>
<!-- links/scripts are prioritized by their utility to early loading, not call order -->
<link rel="prefetch-dns" href="https://...">
<link rel="preconnect" href="https://...">
<link rel="preload" as="font" href="https://.../path/to/font.woff">
<link rel="preload" as="style" href="https://.../path/to/stylesheet.css">
<script async="" src="https://.../path/to/some/script.js"></script>
</head>
<body>
...
</body>
</html>
```
These APIs can be used to optimize initial page loads by moving discovery of additional resources like fonts out of stylesheet loading. They can also make client updates faster by prefetching a list of resources used by an anticipated navigation and then eagerly preloading those resources on click or even on hover.
For more details see [Resource Preloading APIs](https://react.dev/reference/react-dom).
### Compatibility with third-party scripts and extensions[Link for Compatibility with third-party scripts and extensions]()
We’ve improved hydration to account for third-party scripts and browser extensions.
When hydrating, if an element that renders on the client doesn’t match the element found in the HTML from the server, React will force a client re-render to fix up the content. Previously, if an element was inserted by third-party scripts or browser extensions, it would trigger a mismatch error and client render.
In React 19, unexpected tags in the `<head>` and `<body>` will be skipped over, avoiding the mismatch errors. If React needs to re-render the entire document due to an unrelated hydration mismatch, it will leave in place stylesheets inserted by third-party scripts and browser extensions.
### Better error reporting[Link for Better error reporting]()
We improved error handling in React 19 to remove duplication and provide options for handling caught and uncaught errors. For example, when there’s an error in render caught by an Error Boundary, previously React would throw the error twice (once for the original error, then again after failing to automatically recover), and then call `console.error` with info about where the error occurred.
This resulted in three errors for every caught error:
Console
Uncaught Error: hit at Throws at renderWithHooks …
Uncaught Error: hit <-- Duplicate at Throws at renderWithHooks …
The above error occurred in the Throws component: at Throws at ErrorBoundary at App React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
In React 19, we log a single error with all the error information included:
Console
Error: hit at Throws at renderWithHooks … The above error occurred in the Throws component: at Throws at ErrorBoundary at App React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary. at ErrorBoundary at App
Additionally, we’ve added two new root options to complement `onRecoverableError`:
- `onCaughtError`: called when React catches an error in an Error Boundary.
- `onUncaughtError`: called when an error is thrown and not caught by an Error Boundary.
- `onRecoverableError`: called when an error is thrown and automatically recovered.
For more info and examples, see the docs for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot).
### Support for Custom Elements[Link for Support for Custom Elements]()
React 19 adds full support for custom elements and passes all tests on [Custom Elements Everywhere](https://custom-elements-everywhere.com/).
In past versions, using Custom Elements in React has been difficult because React treated unrecognized props as attributes rather than properties. In React 19, we’ve added support for properties that works on the client and during SSR with the following strategy:
- **Server Side Rendering**: props passed to a custom element will render as attributes if their type is a primitive value like `string`, `number`, or the value is `true`. Props with non-primitive types like `object`, `symbol`, `function`, or value `false` will be omitted.
- **Client Side Rendering**: props that match a property on the Custom Element instance will be assigned as properties, otherwise they will be assigned as attributes.
Thanks to [Joey Arhar](https://github.com/josepharhar) for driving the design and implementation of Custom Element support in React.
#### How to upgrade[Link for How to upgrade]()
See the [React 19 Upgrade Guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide) for step-by-step instructions and a full list of breaking and notable changes.
*Note: this post was originally published 04/25/2024 and has been updated to 12/05/2024 with the stable release.*
[PreviousBlog](https://react.dev/blog)
[NextReact Compiler Beta Release and Roadmap](https://react.dev/blog/2024/10/21/react-compiler-beta-release) |
https://react.dev/reference/react-dom | [API Reference](https://react.dev/reference/react)
# React DOM APIs[Link for this heading]()
The `react-dom` package contains methods that are only supported for the web applications (which run in the browser DOM environment). They are not supported for React Native.
* * *
## APIs[Link for APIs]()
These APIs can be imported from your components. They are rarely used:
- [`createPortal`](https://react.dev/reference/react-dom/createPortal) lets you render child components in a different part of the DOM tree.
- [`flushSync`](https://react.dev/reference/react-dom/flushSync) lets you force React to flush a state update and update the DOM synchronously.
## Resource Preloading APIs[Link for Resource Preloading APIs]()
These APIs can be used to make apps faster by pre-loading resources such as scripts, stylesheets, and fonts as soon as you know you need them, for example before navigating to another page where the resources will be used.
[React-based frameworks](https://react.dev/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call these APIs yourself. Consult your framework’s documentation for details.
- [`prefetchDNS`](https://react.dev/reference/react-dom/prefetchDNS) lets you prefetch the IP address of a DNS domain name that you expect to connect to.
- [`preconnect`](https://react.dev/reference/react-dom/preconnect) lets you connect to a server you expect to request resources from, even if you don’t know what resources you’ll need yet.
- [`preload`](https://react.dev/reference/react-dom/preload) lets you fetch a stylesheet, font, image, or external script that you expect to use.
- [`preloadModule`](https://react.dev/reference/react-dom/preloadModule) lets you fetch an ESM module that you expect to use.
- [`preinit`](https://react.dev/reference/react-dom/preinit) lets you fetch and evaluate an external script or fetch and insert a stylesheet.
- [`preinitModule`](https://react.dev/reference/react-dom/preinitModule) lets you fetch and evaluate an ESM module.
* * *
## Entry points[Link for Entry points]()
The `react-dom` package provides two additional entry points:
- [`react-dom/client`](https://react.dev/reference/react-dom/client) contains APIs to render React components on the client (in the browser).
- [`react-dom/server`](https://react.dev/reference/react-dom/server) contains APIs to render React components on the server.
* * *
## Removed APIs[Link for Removed APIs]()
These APIs were removed in React 19:
- [`findDOMNode`](https://18.react.dev/reference/react-dom/findDOMNode): see [alternatives](https://18.react.dev/reference/react-dom/findDOMNode).
- [`hydrate`](https://18.react.dev/reference/react-dom/hydrate): use [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) instead.
- [`render`](https://18.react.dev/reference/react-dom/render): use [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) instead.
- [`unmountComponentAtNode`](https://react.dev/reference/react-dom/unmountComponentAtNode): use [`root.unmount()`](https://react.dev/reference/react-dom/client/createRoot) instead.
- [`renderToNodeStream`](https://18.react.dev/reference/react-dom/server/renderToNodeStream): use [`react-dom/server`](https://react.dev/reference/react-dom/server) APIs instead.
- [`renderToStaticNodeStream`](https://18.react.dev/reference/react-dom/server/renderToStaticNodeStream): use [`react-dom/server`](https://react.dev/reference/react-dom/server) APIs instead.
[Previous<title>](https://react.dev/reference/react-dom/components/title)
[NextcreatePortal](https://react.dev/reference/react-dom/createPortal) |
https://react.dev/community/docs-contributors | [Community](https://react.dev/community)
# Docs Contributors[Link for this heading]()
React documentation is written and maintained by the [React team](https://react.dev/community/team) and [external contributors.](https://github.com/reactjs/react.dev/graphs/contributors) On this page, we’d like to thank a few people who’ve made significant contributions to this site.
## Content[Link for Content]()
- [Rachel Nabors](https://twitter.com/RachelNabors): editing, writing, illustrating
- [Dan Abramov](https://twitter.com/dan_abramov): writing, curriculum design
- [Sylwia Vargas](https://twitter.com/SylwiaVargas): example code
- [Rick Hanlon](https://twitter.com/rickhanlonii): writing
- [David McCabe](https://twitter.com/mcc_abe): writing
- [Sophie Alpert](https://twitter.com/sophiebits): writing
- [Pete Hunt](https://twitter.com/floydophone): writing
- [Andrew Clark](https://twitter.com/acdlite): writing
- [Matt Carroll](https://twitter.com/mattcarrollcode): editing, writing
- [Natalia Tepluhina](https://twitter.com/n_tepluhina): reviews, advice
- [Sebastian Markbåge](https://twitter.com/sebmarkbage): feedback
## Design[Link for Design]()
- [Dan Lebowitz](https://twitter.com/lebo): site design
- [Razvan Gradinar](https://dribbble.com/GradinarRazvan): sandbox design
- [Maggie Appleton](https://maggieappleton.com/): diagram system
- [Sophie Alpert](https://twitter.com/sophiebits): color-coded explanations
## Development[Link for Development]()
- [Jared Palmer](https://twitter.com/jaredpalmer): site development
- [ThisDotLabs](https://www.thisdot.co/) ([Dane Grant](https://twitter.com/danecando), [Dustin Goodman](https://twitter.com/dustinsgoodman)): site development
- [CodeSandbox](https://codesandbox.io/) ([Ives van Hoorne](https://twitter.com/CompuIves), [Alex Moldovan](https://twitter.com/alexnmoldovan), [Jasper De Moor](https://twitter.com/JasperDeMoor), [Danilo Woznica](https://twitter.com/danilowoz)): sandbox integration
- [Dan Abramov](https://twitter.com/dan_abramov): site development
- [Rick Hanlon](https://twitter.com/rickhanlonii): site development
- [Harish Kumar](https://www.strek.in/): development and maintenance
- [Luna Ruan](https://twitter.com/lunaruan): sandbox improvements
We’d also like to thank countless alpha testers and community members who gave us feedback along the way.
[PreviousMeet the Team](https://react.dev/community/team)
[NextTranslations](https://react.dev/community/translations) |
https://react.dev/community/acknowledgements | [Community](https://react.dev/community)
# Acknowledgements[Link for this heading]()
React was originally created by [Jordan Walke.](https://github.com/jordwalke) Today, React has a [dedicated full-time team working on it](https://react.dev/community/team), as well as over a thousand [open source contributors.](https://github.com/facebook/react/graphs/contributors)
## Past contributors[Link for Past contributors]()
We’d like to recognize a few people who have made significant contributions to React and its documentation in the past and have helped maintain them over the years:
- [Almero Steyn](https://github.com/AlmeroSteyn)
- [Andreas Svensson](https://github.com/syranide)
- [Alex Krolick](https://github.com/alexkrolick)
- [Alexey Pyltsyn](https://github.com/lex111)
- [Andrey Lunyov](https://github.com/alunyov)
- [Brandon Dail](https://github.com/aweary)
- [Brian Vaughn](https://github.com/bvaughn)
- [Caleb Meredith](https://github.com/calebmer)
- [Chang Yan](https://github.com/cyan33)
- [Cheng Lou](https://github.com/chenglou)
- [Christoph Nakazawa](https://github.com/cpojer)
- [Christopher Chedeau](https://github.com/vjeux)
- [Clement Hoang](https://github.com/clemmy)
- [Dave McCabe](https://github.com/davidmccabe)
- [Dominic Gannaway](https://github.com/trueadm)
- [Flarnie Marchan](https://github.com/flarnie)
- [Jason Quense](https://github.com/jquense)
- [Jesse Beach](https://github.com/jessebeach)
- [Jessica Franco](https://github.com/Jessidhia)
- [Jim Sproch](https://github.com/jimfb)
- [Josh Duck](https://github.com/joshduck)
- [Joe Critchley](https://github.com/joecritch)
- [Jeff Morrison](https://github.com/jeffmo)
- [Luna Ruan](https://github.com/lunaruan)
- [Kathryn Middleton](https://github.com/kmiddleton14)
- [Keyan Zhang](https://github.com/keyz)
- [Marco Salazar](https://github.com/salazarm)
- [Mengdi Chen](https://github.com/mondaychen)
- [Nat Alison](https://github.com/tesseralis)
- [Nathan Hunzaker](https://github.com/nhunzaker)
- [Nicolas Gallagher](https://github.com/necolas)
- [Paul O’Shannessy](https://github.com/zpao)
- [Pete Hunt](https://github.com/petehunt)
- [Philipp Spiess](https://github.com/philipp-spiess)
- [Rachel Nabors](https://github.com/rachelnabors)
- [Robert Zhang](https://github.com/robertzhidealx)
- [Samuel Susla](https://github.com/sammy-SC)
- [Sander Spies](https://github.com/sanderspies)
- [Sasha Aickin](https://github.com/aickin)
- [Sean Keegan](https://github.com/seanryankeegan)
- [Sophia Shoemaker](https://github.com/mrscobbler)
- [Sunil Pai](https://github.com/threepointone)
- [Tim Yung](https://github.com/yungsters)
- [Xuan Huang](https://github.com/huxpro)
This list is not exhaustive.
We’d like to give special thanks to [Tom Occhino](https://github.com/tomocchino) and [Adam Wolff](https://github.com/wolffiex) for their guidance and support over the years. We are also thankful to all the volunteers who [translated React into other languages.](https://translations.react.dev/)
## Additional Thanks[Link for Additional Thanks]()
Additionally, we’re grateful to:
- [Jeff Barczewski](https://github.com/jeffbski) for allowing us to use the `react` package name on npm
- [Christopher Aue](https://christopheraue.net/) for letting us use the reactjs.com domain name and the [@reactjs](https://twitter.com/reactjs) username on Twitter
- [ProjectMoon](https://github.com/ProjectMoon) for letting us use the [flux](https://www.npmjs.com/package/flux) package name on npm
- Shane Anderson for allowing us to use the [react](https://github.com/react) org on GitHub
[PreviousTranslations](https://react.dev/community/translations)
[NextVersioning Policy](https://react.dev/community/versioning-policy) |
https://react.dev/community/team | [Community](https://react.dev/community)
# Meet the Team[Link for this heading]()
React development is led by a dedicated team working full time at Meta. It also receives contributions from people all over the world.
## React Core[Link for React Core]()
The React Core team members work full time on the core component APIs, the engine that powers React DOM and React Native, React DevTools, and the React documentation website.
Current members of the React team are listed in alphabetical order below.
![Andrew Clark](/_next/image?url=%2Fimages%2Fteam%2Facdlite.jpg&w=3840&q=75)
![Andrew Clark](/_next/image?url=%2Fimages%2Fteam%2Facdlite.jpg&w=3840&q=75)
### Andrew Clark[Link for Andrew Clark]()
Engineer at Vercel
Andrew got started with web development by making sites with WordPress, and eventually tricked himself into doing JavaScript. His favorite pastime is karaoke. Andrew is either a Disney villain or a Disney princess, depending on the day.
[acdlite](https://twitter.com/acdlite)
[acdlite](https://threads.net/acdlite)
[acdlite](https://github.com/acdlite)
![Dan Abramov](/_next/image?url=%2Fimages%2Fteam%2Fgaearon.jpg&w=3840&q=75)
![Dan Abramov](/_next/image?url=%2Fimages%2Fteam%2Fgaearon.jpg&w=3840&q=75)
### Dan Abramov[Link for Dan Abramov]()
Independent Engineer
Dan got into programming after he accidentally discovered Visual Basic inside Microsoft PowerPoint. He has found his true calling in turning [Sebastian]()’s tweets into long-form blog posts. Dan occasionally wins at Fortnite by hiding in a bush until the game ends.
[danabra.mov](https://bsky.app/profile/danabra.mov)
[gaearon](https://github.com/gaearon)
![Eli White](/_next/image?url=%2Fimages%2Fteam%2Feli-white.jpg&w=3840&q=75)
![Eli White](/_next/image?url=%2Fimages%2Fteam%2Feli-white.jpg&w=3840&q=75)
### Eli White[Link for Eli White]()
Engineering Manager at Meta
Eli got into programming after he got suspended from middle school for hacking. He has been working on React and React Native since 2017. He enjoys eating treats, especially ice cream and apple pie. You can find Eli trying quirky activities like parkour, indoor skydiving, and aerial silks.
[Eli\_White](https://twitter.com/Eli_White)
[elicwhite](https://threads.net/elicwhite)
[TheSavior](https://github.com/TheSavior)
![Jack Pope](/_next/image?url=%2Fimages%2Fteam%2Fjack-pope.jpg&w=3840&q=75)
![Jack Pope](/_next/image?url=%2Fimages%2Fteam%2Fjack-pope.jpg&w=3840&q=75)
### Jack Pope[Link for Jack Pope]()
Engineer at Meta
Shortly after being introduced to AutoHotkey, Jack had written scripts to automate everything he could think of. When reaching limitations there, he dove headfirst into web app development and hasn’t looked back. Most recently, Jack worked on the web platform at Instagram before moving to React. His favorite programming language is JSX.
[jackpope](https://github.com/jackpope)
[jackpope.me](https://jackpope.me)
![Jason Bonta](/_next/image?url=%2Fimages%2Fteam%2Fjasonbonta.jpg&w=3840&q=75)
![Jason Bonta](/_next/image?url=%2Fimages%2Fteam%2Fjasonbonta.jpg&w=3840&q=75)
### Jason Bonta[Link for Jason Bonta]()
Engineering Manager at Meta
Jason abandoned embedded C for a career in front-end engineering and never looked back. Armed with esoteric CSS knowledge and a passion for beautiful UI, Jason joined Facebook in 2010, where he now feels privileged to have seen JavaScript development come of age. Though he may not understand how `for...of` loops work, he loves getting to work with brilliant people on projects that enable amazing UX.
[someextent](https://threads.net/someextent)
![Joe Savona](/_next/image?url=%2Fimages%2Fteam%2Fjoe.jpg&w=3840&q=75)
![Joe Savona](/_next/image?url=%2Fimages%2Fteam%2Fjoe.jpg&w=3840&q=75)
### Joe Savona[Link for Joe Savona]()
Engineer at Meta
Joe was planning to major in math and philosophy but got into computer science after writing physics simulations in Matlab. Prior to React, he worked on Relay, RSocket.js, and the Skip programming language. While he’s not building some sort of reactive system he enjoys running, studying Japanese, and spending time with his family.
[en\_JS](https://twitter.com/en_JS)
[joesavona](https://threads.net/joesavona)
[josephsavona](https://github.com/josephsavona)
![Josh Story](/_next/image?url=%2Fimages%2Fteam%2Fjosh.jpg&w=3840&q=75)
![Josh Story](/_next/image?url=%2Fimages%2Fteam%2Fjosh.jpg&w=3840&q=75)
### Josh Story[Link for Josh Story]()
Engineer at Vercel
Josh majored in Mathematics and discovered programming while in college. His first professional developer job was to program insurance rate calculations in Microsoft Excel, the paragon of Reactive Programming which must be why he now works on React. In between that time Josh has been an IC, Manager, and Executive at a few startups. outside of work he likes to push his limits with cooking.
[storyhb.com](https://bsky.app/profile/storyhb.com)
[gnoff](https://github.com/gnoff)
![Lauren Tan](/_next/image?url=%2Fimages%2Fteam%2Flauren.jpg&w=3840&q=75)
![Lauren Tan](/_next/image?url=%2Fimages%2Fteam%2Flauren.jpg&w=3840&q=75)
### Lauren Tan[Link for Lauren Tan]()
Engineer at Meta
Lauren’s programming career peaked when she first discovered the `<marquee>` tag. She’s been chasing that high ever since. She studied Finance instead of CS in college, so she learned to code using Excel. Lauren enjoys dropping cheeky memes in chat, playing video games with her partner, learning Korean, and petting her dog Zelda.
[potetotes](https://twitter.com/potetotes)
[potetotes](https://threads.net/potetotes)
[no.lol](https://bsky.app/profile/no.lol)
[poteto](https://github.com/poteto)
![Luna Wei](/_next/image?url=%2Fimages%2Fteam%2Fluna-wei.jpg&w=3840&q=75)
![Luna Wei](/_next/image?url=%2Fimages%2Fteam%2Fluna-wei.jpg&w=3840&q=75)
### Luna Wei[Link for Luna Wei]()
Engineer at Meta
Luna first learnt the fundamentals of python at the age of 6 from her father. Since then, she has been unstoppable. Luna aspires to be a gen z, and the road to success is paved with environmental advocacy, urban gardening and lots of quality time with her Voo-Doo’d (as pictured).
[lunaleaps](https://twitter.com/lunaleaps)
[lunaleaps](https://threads.net/lunaleaps)
[lunaleaps](https://github.com/lunaleaps)
![Matt Carroll](/_next/image?url=%2Fimages%2Fteam%2Fmatt-carroll.png&w=3840&q=75)
![Matt Carroll](/_next/image?url=%2Fimages%2Fteam%2Fmatt-carroll.png&w=3840&q=75)
### Matt Carroll[Link for Matt Carroll]()
Developer Advocate at Meta
Matt stumbled into coding, and since then, has become enamored with creating things in communities that can’t be created alone. Prior to React, he worked on YouTube, the Google Assistant, Fuchsia, and Google Cloud AI and Evernote. When he’s not trying to make better developer tools he enjoys the mountains, jazz, and spending time with his family.
[mattcarrollcode](https://twitter.com/mattcarrollcode)
[mattcarrollcode](https://threads.net/mattcarrollcode)
[mattcarrollcode](https://github.com/mattcarrollcode)
![Mofei Zhang](/_next/image?url=%2Fimages%2Fteam%2Fmofei-zhang.png&w=3840&q=75)
![Mofei Zhang](/_next/image?url=%2Fimages%2Fteam%2Fmofei-zhang.png&w=3840&q=75)
### Mofei Zhang[Link for Mofei Zhang]()
Engineer at Meta
Mofei started programming when she realized it can help her cheat in video games. She focused on operating systems in undergrad / grad school, but now finds herself happily tinkering on React. Outside of work, she enjoys debugging bouldering problems and planning her next backpacking trip(s).
[z\_mofei](https://threads.net/z_mofei)
[mofeiZ](https://github.com/mofeiZ)
![Noah Lemen](/_next/image?url=%2Fimages%2Fteam%2Fnoahlemen.jpg&w=3840&q=75)
![Noah Lemen](/_next/image?url=%2Fimages%2Fteam%2Fnoahlemen.jpg&w=3840&q=75)
### Noah Lemen[Link for Noah Lemen]()
Engineer at Meta
Noah’s interest in UI programming sparked during his education in music technology at NYU. At Meta, he’s worked on internal tools, browsers, web performance, and is currently focused on React. Outside of work, Noah can be found tinkering with synthesizers or spending time with his cat.
[noahlemen](https://twitter.com/noahlemen)
[noahlemen](https://threads.net/noahlemen)
[noahlemen](https://github.com/noahlemen)
[noahle.men](https://noahle.men)
![Rick Hanlon](/_next/image?url=%2Fimages%2Fteam%2Frickhanlonii.jpg&w=3840&q=75)
![Rick Hanlon](/_next/image?url=%2Fimages%2Fteam%2Frickhanlonii.jpg&w=3840&q=75)
### Rick Hanlon[Link for Rick Hanlon]()
Engineer at Meta
Ricky majored in theoretical math and somehow found himself on the React Native team for a couple years before joining the React team. When he’s not programming you can find him snowboarding, biking, climbing, golfing, or closing GitHub issues that do not match the issue template.
[rickhanlonii](https://twitter.com/rickhanlonii)
[rickhanlonii](https://threads.net/rickhanlonii)
[ricky.fm](https://bsky.app/profile/ricky.fm)
[rickhanlonii](https://github.com/rickhanlonii)
![Ruslan Lesiutin](/_next/image?url=%2Fimages%2Fteam%2Flesiutin.jpg&w=3840&q=75)
![Ruslan Lesiutin](/_next/image?url=%2Fimages%2Fteam%2Flesiutin.jpg&w=3840&q=75)
### Ruslan Lesiutin[Link for Ruslan Lesiutin]()
Engineer at Meta
Ruslan’s introduction to UI programming started when he was a kid by manually editing HTML templates for his custom gaming forums. Somehow, he ended up majoring in Computer Science. He enjoys music, games, and memes. Mostly memes.
[ruslanlesiutin](https://twitter.com/ruslanlesiutin)
[lesiutin](https://threads.net/lesiutin)
[hoxyq](https://github.com/hoxyq)
![Sathya Gunasekaran ](/_next/image?url=%2Fimages%2Fteam%2Fsathya.jpg&w=3840&q=75)
![Sathya Gunasekaran ](/_next/image?url=%2Fimages%2Fteam%2Fsathya.jpg&w=3840&q=75)
### Sathya Gunasekaran[Link for Sathya Gunasekaran]()
Engineer at Meta
Sathya hated the Dragon Book in school but somehow ended up working on compilers all his career. When he’s not compiling React components, he’s either drinking coffee or eating yet another Dosa.
[\_gsathya](https://twitter.com/_gsathya)
[gsathya.03](https://threads.net/gsathya.03)
[gsathya](https://github.com/gsathya)
![Sebastian Markbåge](/_next/image?url=%2Fimages%2Fteam%2Fsebmarkbage.jpg&w=3840&q=75)
![Sebastian Markbåge](/_next/image?url=%2Fimages%2Fteam%2Fsebmarkbage.jpg&w=3840&q=75)
### Sebastian Markbåge[Link for Sebastian Markbåge]()
Engineer at Vercel
Sebastian majored in psychology. He’s usually quiet. Even when he says something, it often doesn’t make sense to the rest of us until a few months later. The correct way to pronounce his surname is “mark-boa-geh” but he settled for “mark-beige” out of pragmatism — and that’s how he approaches React.
[sebmarkbage](https://twitter.com/sebmarkbage)
[sebmarkbage](https://threads.net/sebmarkbage)
[sebmarkbage](https://github.com/sebmarkbage)
![Sebastian Silbermann](/_next/image?url=%2Fimages%2Fteam%2Fsebsilbermann.jpg&w=3840&q=75)
![Sebastian Silbermann](/_next/image?url=%2Fimages%2Fteam%2Fsebsilbermann.jpg&w=3840&q=75)
### Sebastian Silbermann[Link for Sebastian Silbermann]()
Engineer at Vercel
Sebastian learned programming to make the browser games he played during class more enjoyable. Eventually this lead to contributing to as much open source code as possible. Outside of coding he’s busy making sure people don’t confuse him with the other Sebastians and Zilberman of the React community.
[sebsilbermann](https://twitter.com/sebsilbermann)
[sebsilbermann](https://threads.net/sebsilbermann)
[eps1lon](https://github.com/eps1lon)
![Seth Webster](/_next/image?url=%2Fimages%2Fteam%2Fseth.jpg&w=3840&q=75)
![Seth Webster](/_next/image?url=%2Fimages%2Fteam%2Fseth.jpg&w=3840&q=75)
### Seth Webster[Link for Seth Webster]()
Engineering Manager at Meta
Seth started programming as a kid growing up in Tucson, AZ. After school, he was bitten by the music bug and was a touring musician for about 10 years before returning to *work*, starting with Intuit. In his spare time, he loves [taking pictures](https://www.sethwebster.com) and flying for animal rescues in the northeastern United States.
[sethwebster](https://twitter.com/sethwebster)
[sethwebster](https://threads.net/sethwebster)
[sethwebster](https://github.com/sethwebster)
[sethwebster.com](https://sethwebster.com)
![Sophie Alpert](/_next/image?url=%2Fimages%2Fteam%2Fsophiebits.jpg&w=3840&q=75)
![Sophie Alpert](/_next/image?url=%2Fimages%2Fteam%2Fsophiebits.jpg&w=3840&q=75)
### Sophie Alpert[Link for Sophie Alpert]()
Independent Engineer
Four days after React was released, Sophie rewrote the entirety of her then-current project to use it, which she now realizes was perhaps a bit reckless. After she became the project’s #1 committer, she wondered why she wasn’t getting paid by Facebook like everyone else was and joined the team officially to lead React through its adolescent years. Though she quit that job years ago, somehow she’s still in the team’s group chats and “providing value”.
[sophiebits](https://twitter.com/sophiebits)
[sophiebits](https://threads.net/sophiebits)
[sophiebits](https://github.com/sophiebits)
[sophiebits.com](https://sophiebits.com)
![Tianyu Yao](/_next/image?url=%2Fimages%2Fteam%2Ftianyu.jpg&w=3840&q=75)
![Tianyu Yao](/_next/image?url=%2Fimages%2Fteam%2Ftianyu.jpg&w=3840&q=75)
### Tianyu Yao[Link for Tianyu Yao]()
Engineer at Meta
Tianyu’s interest in computers started as a kid because he loves video games. So he majored in computer science and still plays childish games like League of Legends. When he is not in front of a computer, he enjoys playing with his two kittens, hiking and kayaking.
[tianyu0](https://twitter.com/tianyu0)
[tyao1](https://github.com/tyao1)
![Yuzhi Zheng](/_next/image?url=%2Fimages%2Fteam%2Fyuzhi.jpg&w=3840&q=75)
![Yuzhi Zheng](/_next/image?url=%2Fimages%2Fteam%2Fyuzhi.jpg&w=3840&q=75)
### Yuzhi Zheng[Link for Yuzhi Zheng]()
Engineering Manager at Meta
Yuzhi studied Computer Science in school. She liked the instant gratification of seeing code come to life without having to physically be in a laboratory. Now she’s a manager in the React org. Before management, she used to work on the Relay data fetching framework. In her spare time, Yuzhi enjoys optimizing her life via gardening and home improvement projects.
[yuzhiz](https://twitter.com/yuzhiz)
[yuzhiz](https://threads.net/yuzhiz)
[yuzhi](https://github.com/yuzhi)
## Past contributors[Link for Past contributors]()
You can find the past team members and other people who significantly contributed to React over the years on the [acknowledgements](https://react.dev/community/acknowledgements) page.
[PreviousReact Videos](https://react.dev/community/videos)
[NextDocs Contributors](https://react.dev/community/docs-contributors) |
https://react.dev/learn/escape-hatches | [Learn React](https://react.dev/learn)
# Escape Hatches[Link for this heading]()
Advanced
Some of your components may need to control and synchronize with systems outside of React. For example, you might need to focus an input using the browser API, play and pause a video player implemented without React, or connect and listen to messages from a remote server. In this chapter, you’ll learn the escape hatches that let you “step outside” React and connect to external systems. Most of your application logic and data flow should not rely on these features.
### In this chapter
- [How to “remember” information without re-rendering](https://react.dev/learn/referencing-values-with-refs)
- [How to access DOM elements managed by React](https://react.dev/learn/manipulating-the-dom-with-refs)
- [How to synchronize components with external systems](https://react.dev/learn/synchronizing-with-effects)
- [How to remove unnecessary Effects from your components](https://react.dev/learn/you-might-not-need-an-effect)
- [How an Effect’s lifecycle is different from a component’s](https://react.dev/learn/lifecycle-of-reactive-effects)
- [How to prevent some values from re-triggering Effects](https://react.dev/learn/separating-events-from-effects)
- [How to make your Effect re-run less often](https://react.dev/learn/removing-effect-dependencies)
- [How to share logic between components](https://react.dev/learn/reusing-logic-with-custom-hooks)
## Referencing values with refs[Link for Referencing values with refs]()
When you want a component to “remember” some information, but you don’t want that information to [trigger new renders](https://react.dev/learn/render-and-commit), you can use a *ref*:
```
const ref = useRef(0);
```
Like state, refs are retained by React between re-renders. However, setting state re-renders a component. Changing a ref does not! You can access the current value of that ref through the `ref.current` property.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef } from 'react';
export default function Counter() {
let ref = useRef(0);
function handleClick() {
ref.current = ref.current + 1;
alert('You clicked ' + ref.current + ' times!');
}
return (
<button onClick={handleClick}>
Click me!
</button>
);
}
```
Show more
A ref is like a secret pocket of your component that React doesn’t track. For example, you can use refs to store [timeout IDs](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout), [DOM elements](https://developer.mozilla.org/en-US/docs/Web/API/Element), and other objects that don’t impact the component’s rendering output.
## Ready to learn this topic?
Read [**Referencing Values with Refs**](https://react.dev/learn/referencing-values-with-refs) to learn how to use refs to remember information.
[Read More](https://react.dev/learn/referencing-values-with-refs)
* * *
## Manipulating the DOM with refs[Link for Manipulating the DOM with refs]()
React automatically updates the DOM to match your render output, so your components won’t often need to manipulate it. However, sometimes you might need access to the DOM elements managed by React—for example, to focus a node, scroll to it, or measure its size and position. There is no built-in way to do those things in React, so you will need a ref to the DOM node. For example, clicking the button will focus the input using a ref:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>
Focus the input
</button>
</>
);
}
```
Show more
## Ready to learn this topic?
Read [**Manipulating the DOM with Refs**](https://react.dev/learn/manipulating-the-dom-with-refs) to learn how to access DOM elements managed by React.
[Read More](https://react.dev/learn/manipulating-the-dom-with-refs)
* * *
## Synchronizing with Effects[Link for Synchronizing with Effects]()
Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. Unlike event handlers, which let you handle particular events, *Effects* let you run some code after rendering. Use them to synchronize your component with a system outside of React.
Press Play/Pause a few times and see how the video player stays synchronized to the `isPlaying` prop value:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useRef, useEffect } from 'react';
function VideoPlayer({ src, isPlaying }) {
const ref = useRef(null);
useEffect(() => {
if (isPlaying) {
ref.current.play();
} else {
ref.current.pause();
}
}, [isPlaying]);
return <video ref={ref} src={src} loop playsInline />;
}
export default function App() {
const [isPlaying, setIsPlaying] = useState(false);
return (
<>
<button onClick={() => setIsPlaying(!isPlaying)}>
{isPlaying ? 'Pause' : 'Play'}
</button>
<VideoPlayer
isPlaying={isPlaying}
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
/>
</>
);
}
```
Show more
Many Effects also “clean up” after themselves. For example, an Effect that sets up a connection to a chat server should return a *cleanup function* that tells React how to disconnect your component from that server:
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
export default function ChatRoom() {
useEffect(() => {
const connection = createConnection();
connection.connect();
return () => connection.disconnect();
}, []);
return <h1>Welcome to the chat!</h1>;
}
```
In development, React will immediately run and clean up your Effect one extra time. This is why you see `"✅ Connecting..."` printed twice. This ensures that you don’t forget to implement the cleanup function.
## Ready to learn this topic?
Read [**Synchronizing with Effects**](https://react.dev/learn/synchronizing-with-effects) to learn how to synchronize components with external systems.
[Read More](https://react.dev/learn/synchronizing-with-effects)
* * *
## You Might Not Need An Effect[Link for You Might Not Need An Effect]()
Effects are an escape hatch from the React paradigm. They let you “step outside” of React and synchronize your components with some external system. If there is no external system involved (for example, if you want to update a component’s state when some props or state change), you shouldn’t need an Effect. Removing unnecessary Effects will make your code easier to follow, faster to run, and less error-prone.
There are two common cases in which you don’t need Effects:
- **You don’t need Effects to transform data for rendering.**
- **You don’t need Effects to handle user events.**
For example, you don’t need an Effect to adjust some state based on other state:
```
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
// 🔴 Avoid: redundant state and unnecessary Effect
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
// ...
}
```
Instead, calculate as much as you can while rendering:
```
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
// ✅ Good: calculated during rendering
const fullName = firstName + ' ' + lastName;
// ...
}
```
However, you *do* need Effects to synchronize with external systems.
## Ready to learn this topic?
Read [**You Might Not Need an Effect**](https://react.dev/learn/you-might-not-need-an-effect) to learn how to remove unnecessary Effects.
[Read More](https://react.dev/learn/you-might-not-need-an-effect)
* * *
## Lifecycle of reactive effects[Link for Lifecycle of reactive effects]()
Effects have a different lifecycle from components. Components may mount, update, or unmount. An Effect can only do two things: to start synchronizing something, and later to stop synchronizing it. This cycle can happen multiple times if your Effect depends on props and state that change over time.
This Effect depends on the value of the `roomId` prop. Props are *reactive values,* which means they can change on a re-render. Notice that the Effect *re-synchronizes* (and re-connects to the server) if `roomId` changes:
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to the {roomId} room!</h1>;
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}
```
Show more
React provides a linter rule to check that you’ve specified your Effect’s dependencies correctly. If you forget to specify `roomId` in the list of dependencies in the above example, the linter will find that bug automatically.
## Ready to learn this topic?
Read [**Lifecycle of Reactive Events**](https://react.dev/learn/lifecycle-of-reactive-effects) to learn how an Effect’s lifecycle is different from a component’s.
[Read More](https://react.dev/learn/lifecycle-of-reactive-effects)
* * *
## Separating events from Effects[Link for Separating events from Effects]()
### Under Construction
This section describes an **experimental API that has not yet been released** in a stable version of React.
Event handlers only re-run when you perform the same interaction again. Unlike event handlers, Effects re-synchronize if any of the values they read, like props or state, are different than during last render. Sometimes, you want a mix of both behaviors: an Effect that re-runs in response to some values but not others.
All code inside Effects is *reactive.* It will run again if some reactive value it reads has changed due to a re-render. For example, this Effect will re-connect to the chat if either `roomId` or `theme` have changed:
App.jschat.jsnotifications.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection, sendMessage } from './chat.js';
import { showNotification } from './notifications.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId, theme }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
showNotification('Connected!', theme);
});
connection.connect();
return () => connection.disconnect();
}, [roomId, theme]);
return <h1>Welcome to the {roomId} room!</h1>
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [isDark, setIsDark] = useState(false);
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<label>
<input
type="checkbox"
checked={isDark}
onChange={e => setIsDark(e.target.checked)}
/>
Use dark theme
</label>
<hr />
<ChatRoom
roomId={roomId}
theme={isDark ? 'dark' : 'light'}
/>
</>
);
}
```
Show more
This is not ideal. You want to re-connect to the chat only if the `roomId` has changed. Switching the `theme` shouldn’t re-connect to the chat! Move the code reading `theme` out of your Effect into an *Effect Event*:
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { experimental_useEffectEvent as useEffectEvent } from 'react';
import { createConnection, sendMessage } from './chat.js';
import { showNotification } from './notifications.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
showNotification('Connected!', theme);
});
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
onConnected();
});
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to the {roomId} room!</h1>
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [isDark, setIsDark] = useState(false);
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<label>
<input
type="checkbox"
checked={isDark}
onChange={e => setIsDark(e.target.checked)}
/>
Use dark theme
</label>
<hr />
<ChatRoom
roomId={roomId}
theme={isDark ? 'dark' : 'light'}
/>
</>
);
}
```
Show more
Code inside Effect Events isn’t reactive, so changing the `theme` no longer makes your Effect re-connect.
## Ready to learn this topic?
Read [**Separating Events from Effects**](https://react.dev/learn/separating-events-from-effects) to learn how to prevent some values from re-triggering Effects.
[Read More](https://react.dev/learn/separating-events-from-effects)
* * *
## Removing Effect dependencies[Link for Removing Effect dependencies]()
When you write an Effect, the linter will verify that you’ve included every reactive value (like props and state) that the Effect reads in the list of your Effect’s dependencies. This ensures that your Effect remains synchronized with the latest props and state of your component. Unnecessary dependencies may cause your Effect to run too often, or even create an infinite loop. The way you remove them depends on the case.
For example, this Effect depends on the `options` object which gets re-created every time you edit the input:
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const options = {
serverUrl: serverUrl,
roomId: roomId
};
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]);
return (
<>
<h1>Welcome to the {roomId} room!</h1>
<input value={message} onChange={e => setMessage(e.target.value)} />
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}
```
Show more
You don’t want the chat to re-connect every time you start typing a message in that chat. To fix this problem, move creation of the `options` object inside the Effect so that the Effect only depends on the `roomId` string:
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
const options = {
serverUrl: serverUrl,
roomId: roomId
};
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return (
<>
<h1>Welcome to the {roomId} room!</h1>
<input value={message} onChange={e => setMessage(e.target.value)} />
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}
```
Show more
Notice that you didn’t start by editing the dependency list to remove the `options` dependency. That would be wrong. Instead, you changed the surrounding code so that the dependency became *unnecessary.* Think of the dependency list as a list of all the reactive values used by your Effect’s code. You don’t intentionally choose what to put on that list. The list describes your code. To change the dependency list, change the code.
## Ready to learn this topic?
Read [**Removing Effect Dependencies**](https://react.dev/learn/removing-effect-dependencies) to learn how to make your Effect re-run less often.
[Read More](https://react.dev/learn/removing-effect-dependencies)
* * *
## Reusing logic with custom Hooks[Link for Reusing logic with custom Hooks]()
React comes with built-in Hooks like `useState`, `useContext`, and `useEffect`. Sometimes, you’ll wish that there was a Hook for some more specific purpose: for example, to fetch data, to keep track of whether the user is online, or to connect to a chat room. To do this, you can create your own Hooks for your application’s needs.
In this example, the `usePointerPosition` custom Hook tracks the cursor position, while `useDelayedValue` custom Hook returns a value that’s “lagging behind” the value you passed by a certain number of milliseconds. Move the cursor over the sandbox preview area to see a moving trail of dots following the cursor:
App.jsusePointerPosition.jsuseDelayedValue.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { usePointerPosition } from './usePointerPosition.js';
import { useDelayedValue } from './useDelayedValue.js';
export default function Canvas() {
const pos1 = usePointerPosition();
const pos2 = useDelayedValue(pos1, 100);
const pos3 = useDelayedValue(pos2, 200);
const pos4 = useDelayedValue(pos3, 100);
const pos5 = useDelayedValue(pos4, 50);
return (
<>
<Dot position={pos1} opacity={1} />
<Dot position={pos2} opacity={0.8} />
<Dot position={pos3} opacity={0.6} />
<Dot position={pos4} opacity={0.4} />
<Dot position={pos5} opacity={0.2} />
</>
);
}
function Dot({ position, opacity }) {
return (
<div style={{
position: 'absolute',
backgroundColor: 'pink',
borderRadius: '50%',
opacity,
transform: `translate(${position.x}px, ${position.y}px)`,
pointerEvents: 'none',
left: -20,
top: -20,
width: 40,
height: 40,
}} />
);
}
```
Show more
You can create custom Hooks, compose them together, pass data between them, and reuse them between components. As your app grows, you will write fewer Effects by hand because you’ll be able to reuse custom Hooks you already wrote. There are also many excellent custom Hooks maintained by the React community.
## Ready to learn this topic?
Read [**Reusing Logic with Custom Hooks**](https://react.dev/learn/reusing-logic-with-custom-hooks) to learn how to share logic between components.
[Read More](https://react.dev/learn/reusing-logic-with-custom-hooks)
* * *
## What’s next?[Link for What’s next?]()
Head over to [Referencing Values with Refs](https://react.dev/learn/referencing-values-with-refs) to start reading this chapter page by page!
[PreviousScaling Up with Reducer and Context](https://react.dev/learn/scaling-up-with-reducer-and-context)
[NextReferencing Values with Refs](https://react.dev/learn/referencing-values-with-refs) |
https://react.dev/community/videos | [Community](https://react.dev/community)
# React Videos[Link for this heading]()
Videos dedicated to the discussion of React and the React ecosystem.
## React Conf 2021[Link for React Conf 2021]()
### React 18 Keynote[Link for React 18 Keynote]()
In the keynote, we shared our vision for the future of React starting with React 18.
Watch the full keynote from [Andrew Clark](https://twitter.com/acdlite), [Juan Tejada](https://twitter.com/_jstejada), [Lauren Tan](https://twitter.com/potetotes), and [Rick Hanlon](https://twitter.com/rickhanlonii) here:
### React 18 for Application Developers[Link for React 18 for Application Developers]()
For a demo of upgrading to React 18, see [Shruti Kapoor](https://twitter.com/shrutikapoor08)’s talk here:
### Streaming Server Rendering with Suspense[Link for Streaming Server Rendering with Suspense]()
React 18 also includes improvements to server-side rendering performance using Suspense.
Streaming server rendering lets you generate HTML from React components on the server, and stream that HTML to your users. In React 18, you can use `Suspense` to break down your app into smaller independent units which can be streamed independently of each other without blocking the rest of the app. This means users will see your content sooner and be able to start interacting with it much faster.
For a deep dive, see [Shaundai Person](https://twitter.com/shaundai)’s talk here:
### The first React working group[Link for The first React working group]()
For React 18, we created our first Working Group to collaborate with a panel of experts, developers, library maintainers, and educators. Together we worked to create our gradual adoption strategy and refine new APIs such as `useId`, `useSyncExternalStore`, and `useInsertionEffect`.
For an overview of this work, see [Aakansha’ Doshi](https://twitter.com/aakansha1216)’s talk:
### React Developer Tooling[Link for React Developer Tooling]()
To support the new features in this release, we also announced the newly formed React DevTools team and a new Timeline Profiler to help developers debug their React apps.
For more information and a demo of new DevTools features, see [Brian Vaughn](https://twitter.com/brian_d_vaughn)’s talk:
### React without memo[Link for React without memo]()
Looking further into the future, [Xuan Huang (黄玄)](https://twitter.com/Huxpro) shared an update from our React Labs research into an auto-memoizing compiler. Check out this talk for more information and a demo of the compiler prototype:
### React docs keynote[Link for React docs keynote]()
[Rachel Nabors](https://twitter.com/rachelnabors) kicked off a section of talks about learning and designing with React with a keynote about our investment in React’s new docs ([now shipped as react.dev](https://react.dev/blog/2023/03/16/introducing-react-dev)):
### And more…[Link for And more…]()
**We also heard talks on learning and designing with React:**
- Debbie O’Brien: [Things I learnt from the new React docs](https://youtu.be/-7odLW_hG7s).
- Sarah Rainsberger: [Learning in the Browser](https://youtu.be/5X-WEQflCL0).
- Linton Ye: [The ROI of Designing with React](https://youtu.be/7cPWmID5XAk).
- Delba de Oliveira: [Interactive playgrounds with React](https://youtu.be/zL8cz2W0z34).
**Talks from the Relay, React Native, and PyTorch teams:**
- Robert Balicki: [Re-introducing Relay](https://youtu.be/lhVGdErZuN4).
- Eric Rozell and Steven Moyes: [React Native Desktop](https://youtu.be/9L4FFrvwJwY).
- Roman Rädle: [On-device Machine Learning for React Native](https://youtu.be/NLj73vrc2I8)
**And talks from the community on accessibility, tooling, and Server Components:**
- Daishi Kato: [React 18 for External Store Libraries](https://youtu.be/oPfSC5bQPR8).
- Diego Haz: [Building Accessible Components in React 18](https://youtu.be/dcm8fjBfro8).
- Tafu Nakazaki: [Accessible Japanese Form Components with React](https://youtu.be/S4a0QlsH0pU).
- Lyle Troxell: [UI tools for artists](https://youtu.be/b3l4WxipFsE).
- Helen Lin: [Hydrogen + React 18](https://youtu.be/HS6vIYkSNks).
## Older videos[Link for Older videos]()
### React Conf 2019[Link for React Conf 2019]()
A playlist of videos from React Conf 2019.
### React Conf 2018[Link for React Conf 2018]()
A playlist of videos from React Conf 2018.
### React.js Conf 2017[Link for React.js Conf 2017]()
A playlist of videos from React.js Conf 2017.
### React.js Conf 2016[Link for React.js Conf 2016]()
A playlist of videos from React.js Conf 2016.
### React.js Conf 2015[Link for React.js Conf 2015]()
A playlist of videos from React.js Conf 2015.
### Rethinking Best Practices[Link for Rethinking Best Practices]()
Pete Hunt’s talk at JSConf EU 2013 covers three topics: throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events - (2013 - 0h30m).
### Introduction to React[Link for Introduction to React]()
Tom Occhino and Jordan Walke introduce React at Facebook Seattle - (2013 - 1h20m).
[PreviousReact Meetups](https://react.dev/community/meetups)
[NextMeet the Team](https://react.dev/community/team) |
https://react.dev/community/meetups | [Community](https://react.dev/community)
# React Meetups[Link for this heading]()
Do you have a local React.js meetup? Add it here! (Please keep the list alphabetical)
## Albania[Link for Albania]()
- [Tirana](https://www.meetup.com/React-User-Group-Albania/)
## Argentina[Link for Argentina]()
- [Buenos Aires](https://www.meetup.com/es/React-en-Buenos-Aires)
- [Rosario](https://www.meetup.com/es/reactrosario)
## Australia[Link for Australia]()
- [Brisbane](https://www.meetup.com/reactbris/)
- [Melbourne](https://www.meetup.com/React-Melbourne/)
- [Sydney](https://www.meetup.com/React-Sydney/)
## Austria[Link for Austria]()
- [Vienna](https://www.meetup.com/Vienna-ReactJS-Meetup/)
## Belgium[Link for Belgium]()
- [Belgium](https://www.meetup.com/ReactJS-Belgium/)
## Brazil[Link for Brazil]()
- [Belo Horizonte](https://www.meetup.com/reactbh/)
- [Curitiba](https://www.meetup.com/pt-br/ReactJS-CWB/)
- [Florianópolis](https://www.meetup.com/pt-br/ReactJS-Floripa/)
- [Joinville](https://www.meetup.com/pt-BR/React-Joinville/)
- [São Paulo](https://www.meetup.com/pt-BR/ReactJS-SP/)
## Bolivia[Link for Bolivia]()
- [Bolivia](https://www.meetup.com/ReactBolivia/)
## Canada[Link for Canada]()
- [Halifax, NS](https://www.meetup.com/Halifax-ReactJS-Meetup/)
- [Montreal, QC - React Native](https://www.meetup.com/fr-FR/React-Native-MTL/)
- [Vancouver, BC](https://www.meetup.com/ReactJS-Vancouver-Meetup/)
- [Ottawa, ON](https://www.meetup.com/Ottawa-ReactJS-Meetup/)
- [Saskatoon, SK](https://www.meetup.com/saskatoon-react-meetup/)
- [Toronto, ON](https://www.meetup.com/Toronto-React-Native/events/)
## Colombia[Link for Colombia]()
- [Medellin](https://www.meetup.com/React-Medellin/)
## Denmark[Link for Denmark]()
- [Aalborg](https://www.meetup.com/Aalborg-React-React-Native-Meetup/)
- [Aarhus](https://www.meetup.com/Aarhus-ReactJS-Meetup/)
## England (UK)[Link for England (UK)]()
- [Manchester](https://www.meetup.com/Manchester-React-User-Group/)
- [React.JS Girls London](https://www.meetup.com/ReactJS-Girls-London/)
- [React Advanced London](https://guild.host/react-advanced-london)
- [React Native London](https://guild.host/RNLDN)
## France[Link for France]()
- [Lille](https://www.meetup.com/ReactBeerLille/)
- [Paris](https://www.meetup.com/ReactJS-Paris/)
## Germany[Link for Germany]()
- [Cologne](https://www.meetup.com/React-Cologne/)
- [Düsseldorf](https://www.meetup.com/de-DE/ReactJS-Meetup-Dusseldorf/)
- [Hamburg](https://www.meetup.com/Hamburg-React-js-Meetup/)
- [Karlsruhe](https://www.meetup.com/react_ka/)
- [Kiel](https://www.meetup.com/Kiel-React-Native-Meetup/)
- [Munich](https://www.meetup.com/ReactJS-Meetup-Munich/)
- [React Berlin](https://guild.host/react-berlin)
## Greece[Link for Greece]()
- [Athens](https://www.meetup.com/React-To-React-Athens-MeetUp/)
- [Thessaloniki](https://www.meetup.com/Thessaloniki-ReactJS-Meetup/)
## India[Link for India]()
- [Ahmedabad](https://www.meetup.com/react-ahmedabad/)
- [Bangalore (React)](https://www.meetup.com/ReactJS-Bangalore/)
- [Bangalore (React Native)](https://www.meetup.com/React-Native-Bangalore-Meetup)
- [Chennai](https://www.linkedin.com/company/chennaireact)
- [Delhi NCR](https://www.meetup.com/React-Delhi-NCR/)
- [Mumbai](https://reactmumbai.dev)
- [Pune](https://www.meetup.com/ReactJS-and-Friends/)
## Indonesia[Link for Indonesia]()
- [Indonesia](https://www.meetup.com/reactindonesia/)
## Ireland[Link for Ireland]()
- [Dublin](https://guild.host/reactjs-dublin)
## Israel[Link for Israel]()
- [Tel Aviv](https://www.meetup.com/ReactJS-Israel/)
## Italy[Link for Italy]()
- [Milan](https://www.meetup.com/React-JS-Milano/)
## Japan[Link for Japan]()
- [Osaka](https://react-osaka.connpass.com/)
## Kenya[Link for Kenya]()
- [Nairobi - Reactdevske](https://kommunity.com/reactjs-developer-community-kenya-reactdevske)
## Malaysia[Link for Malaysia]()
- [Kuala Lumpur](https://www.kl-react.com/)
- [Penang](https://www.facebook.com/groups/reactpenang/)
## Netherlands[Link for Netherlands]()
- [Amsterdam](https://guild.host/react-amsterdam)
## New Zealand[Link for New Zealand]()
- [Wellington](https://www.meetup.com/React-Wellington/)
## Norway[Link for Norway]()
- [Norway](https://reactjs-norway.webflow.io/)
- [Oslo](https://www.meetup.com/ReactJS-Oslo-Meetup/)
## Pakistan[Link for Pakistan]()
- [Karachi](https://www.facebook.com/groups/902678696597634/)
- [Lahore](https://www.facebook.com/groups/ReactjsLahore/)
## Philippines[Link for Philippines]()
- [Manila](https://www.meetup.com/reactjs-developers-manila/)
- [Manila - ReactJS PH](https://www.meetup.com/ReactJS-Philippines/)
## Poland[Link for Poland]()
- [Warsaw](https://www.meetup.com/React-js-Warsaw/)
- [Wrocław](https://www.meetup.com/ReactJS-Wroclaw/)
## Portugal[Link for Portugal]()
- [Lisbon](https://www.meetup.com/JavaScript-Lisbon/)
## Scotland (UK)[Link for Scotland (UK)]()
- [Edinburgh](https://www.meetup.com/React-Scotland/)
## Spain[Link for Spain]()
- [Barcelona](https://www.meetup.com/ReactJS-Barcelona/)
## Sweden[Link for Sweden]()
- [Goteborg](https://www.meetup.com/ReactJS-Goteborg/)
- [Stockholm](https://www.meetup.com/Stockholm-ReactJS-Meetup/)
## Switzerland[Link for Switzerland]()
- [Zurich](https://www.meetup.com/Zurich-ReactJS-Meetup/)
## Turkey[Link for Turkey]()
- [Istanbul](https://kommunity.com/reactjs-istanbul)
## Ukraine[Link for Ukraine]()
- [Kyiv](https://www.meetup.com/Kyiv-ReactJS-Meetup)
## US[Link for US]()
- [Atlanta, GA - ReactJS](https://www.meetup.com/React-ATL/)
- [Austin, TX - ReactJS](https://www.meetup.com/ReactJS-Austin-Meetup/)
- [Boston, MA - ReactJS](https://www.meetup.com/ReactJS-Boston/)
- [Boston, MA - React Native](https://www.meetup.com/Boston-React-Native-Meetup/)
- [Charlotte, NC - ReactJS](https://www.meetup.com/ReactJS-Charlotte/)
- [Charlotte, NC - React Native](https://www.meetup.com/cltreactnative/)
- [Chicago, IL - ReactJS](https://www.meetup.com/React-Chicago/)
- [Cleveland, OH - ReactJS](https://www.meetup.com/Cleveland-React/)
- [Columbus, OH - ReactJS](https://www.meetup.com/ReactJS-Columbus-meetup/)
- [Dallas, TX - ReactJS](https://www.meetup.com/ReactDallas/)
- [Detroit, MI - Detroit React User Group](https://www.meetup.com/Detroit-React-User-Group/)
- [Indianapolis, IN - React.Indy](https://www.meetup.com/React-Indy)
- [Irvine, CA - ReactJS](https://www.meetup.com/ReactJS-OC/)
- [Kansas City, MO - ReactJS](https://www.meetup.com/Kansas-City-React-Meetup/)
- [Las Vegas, NV - ReactJS](https://www.meetup.com/ReactVegas/)
- [Leesburg, VA - ReactJS](https://www.meetup.com/React-NOVA/)
- [Los Angeles, CA - ReactJS](https://www.meetup.com/socal-react/)
- [Los Angeles, CA - React Native](https://www.meetup.com/React-Native-Los-Angeles/)
- [Miami, FL - ReactJS](https://www.meetup.com/React-Miami/)
- [New York, NY - ReactJS](https://www.meetup.com/NYC-Javascript-React-Group/)
- [New York, NY - React Ladies](https://www.meetup.com/React-Ladies/)
- [New York, NY - React Native](https://www.meetup.com/React-Native-NYC/)
- [New York, NY - useReactNYC](https://www.meetup.com/useReactNYC/)
- [New York, NY - React.NYC](https://guild.host/react-nyc)
- [Palo Alto, CA - React Native](https://www.meetup.com/React-Native-Silicon-Valley/)
- [Phoenix, AZ - ReactJS](https://www.meetup.com/ReactJS-Phoenix/)
- [Provo, UT - ReactJS](https://www.meetup.com/ReactJS-Utah/)
- [San Diego, CA - San Diego JS](https://www.meetup.com/sandiegojs/)
- [San Francisco - Real World React](https://www.meetup.com/Real-World-React)
- [San Francisco - ReactJS](https://www.meetup.com/ReactJS-San-Francisco/)
- [San Francisco, CA - React Native](https://www.meetup.com/React-Native-San-Francisco/)
- [Santa Monica, CA - ReactJS](https://www.meetup.com/Los-Angeles-ReactJS-User-Group/)
- [Seattle, WA - ReactJS](https://www.meetup.com/seattle-react-js/)
- [Tampa, FL - ReactJS](https://www.meetup.com/ReactJS-Tampa-Bay/)
- [Tucson, AZ - ReactJS](https://www.meetup.com/Tucson-ReactJS-Meetup/)
- [Washington, DC - ReactJS](https://www.meetup.com/React-DC/)
[PreviousReact Conferences](https://react.dev/community/conferences)
[NextReact Videos](https://react.dev/community/videos) |
https://react.dev/community/versioning-policy | [Community](https://react.dev/community)
# Versioning Policy[Link for this heading]()
All stable builds of React go through a high level of testing and follow semantic versioning (semver). React also offers unstable release channels to encourage early feedback on experimental features. This page describes what you can expect from React releases.
For a list of previous releases, see the [Versions](https://react.dev/versions) page.
## Stable releases[Link for Stable releases]()
Stable React releases (also known as “Latest” release channel) follow [semantic versioning (semver)](https://semver.org/) principles.
That means that with a version number **x.y.z**:
- When releasing **critical bug fixes**, we make a **patch release** by changing the **z** number (ex: 15.6.2 to 15.6.3).
- When releasing **new features** or **non-critical fixes**, we make a **minor release** by changing the **y** number (ex: 15.6.2 to 15.7.0).
- When releasing **breaking changes**, we make a **major release** by changing the **x** number (ex: 15.6.2 to 16.0.0).
Major releases can also contain new features, and any release can include bug fixes.
Minor releases are the most common type of release.
### Breaking Changes[Link for Breaking Changes]()
Breaking changes are inconvenient for everyone, so we try to minimize the number of major releases – for example, React 15 was released in April 2016 and React 16 was released in September 2017, and React 17 was released in October 2020.
Instead, we release new features in minor versions. That means that minor releases are often more interesting and compelling than majors, despite their unassuming name.
### Commitment to stability[Link for Commitment to stability]()
As we change React over time, we try to minimize the effort required to take advantage of new features. When possible, we’ll keep an older API working, even if that means putting it in a separate package. For example, [mixins have been discouraged for years](https://legacy.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html) but they’re supported to this day [via create-react-class](https://legacy.reactjs.org/docs/react-without-es6.html) and many codebases continue to use them in stable, legacy code.
Over a million developers use React, collectively maintaining millions of components. The Facebook codebase alone has over 50,000 React components. That means we need to make it as easy as possible to upgrade to new versions of React; if we make large changes without a migration path, people will be stuck on old versions. We test these upgrade paths on Facebook itself – if our team of less than 10 people can update 50,000+ components alone, we hope the upgrade will be manageable for anyone using React. In many cases, we write [automated scripts](https://github.com/reactjs/react-codemod) to upgrade component syntax, which we then include in the open-source release for everyone to use.
### Gradual upgrades via warnings[Link for Gradual upgrades via warnings]()
Development builds of React include many helpful warnings. Whenever possible, we add warnings in preparation for future breaking changes. That way, if your app has no warnings on the latest release, it will be compatible with the next major release. This allows you to upgrade your apps one component at a time.
Development warnings won’t affect the runtime behavior of your app. That way, you can feel confident that your app will behave the same way between the development and production builds — the only differences are that the production build won’t log the warnings and that it is more efficient. (If you ever notice otherwise, please file an issue.)
### What counts as a breaking change?[Link for What counts as a breaking change?]()
In general, we *don’t* bump the major version number for changes to:
- **Development warnings.** Since these don’t affect production behavior, we may add new warnings or modify existing warnings in between major versions. In fact, this is what allows us to reliably warn about upcoming breaking changes.
- **APIs starting with `unstable_`.** These are provided as experimental features whose APIs we are not yet confident in. By releasing these with an `unstable_` prefix, we can iterate faster and get to a stable API sooner.
- **Alpha and Canary versions of React.** We provide alpha versions of React as a way to test new features early, but we need the flexibility to make changes based on what we learn in the alpha period. If you use these versions, note that APIs may change before the stable release.
- **Undocumented APIs and internal data structures.** If you access internal property names like `__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED` or `__reactInternalInstance$uk43rzhitjg`, there is no warranty. You are on your own.
This policy is designed to be pragmatic: certainly, we don’t want to cause headaches for you. If we bumped the major version for all of these changes, we would end up releasing more major versions and ultimately causing more versioning pain for the community. It would also mean that we can’t make progress in improving React as fast as we’d like.
That said, if we expect that a change on this list will cause broad problems in the community, we will still do our best to provide a gradual migration path.
### If a minor release includes no new features, why isn’t it a patch?[Link for If a minor release includes no new features, why isn’t it a patch?]()
It’s possible that a minor release will not include new features. [This is allowed by semver](https://semver.org/), which states **“\[a minor version] MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes.”**
However, it does raise the question of why these releases aren’t versioned as patches instead.
The answer is that any change to React (or other software) carries some risk of breaking in unexpected ways. Imagine a scenario where a patch release that fixes one bug accidentally introduces a different bug. This would not only be disruptive to developers, but also harm their confidence in future patch releases. It’s especially regrettable if the original fix is for a bug that is rarely encountered in practice.
We have a pretty good track record for keeping React releases free of bugs, but patch releases have an even higher bar for reliability because most developers assume they can be adopted without adverse consequences.
For these reasons, we reserve patch releases only for the most critical bugs and security vulnerabilities.
If a release includes non-essential changes — such as internal refactors, changes to implementation details, performance improvements, or minor bugfixes — we will bump the minor version even when there are no new features.
## All release channels[Link for All release channels]()
React relies on a thriving open source community to file bug reports, open pull requests, and [submit RFCs](https://github.com/reactjs/rfcs). To encourage feedback we sometimes share special builds of React that include unreleased features.
### Note
This section will be most relevant to developers who work on frameworks, libraries, or developer tooling. Developers who use React primarily to build user-facing applications should not need to worry about our prerelease channels.
Each of React’s release channels is designed for a distinct use case:
- [**Latest**]() is for stable, semver React releases. It’s what you get when you install React from npm. This is the channel you’re already using today. **User-facing applications that consume React directly use this channel.**
- [**Canary**]() tracks the main branch of the React source code repository. Think of these as release candidates for the next semver release. **[Frameworks or other curated setups may choose to use this channel with a pinned version of React.](https://react.dev/blog/2023/05/03/react-canaries) You can also use Canaries for integration testing between React and third party projects.**
- [**Experimental**]() includes experimental APIs and features that aren’t available in the stable releases. These also track the main branch, but with additional feature flags turned on. Use this to try out upcoming features before they are released.
All releases are published to npm, but only Latest uses semantic versioning. Prereleases (those in the Canary and Experimental channels) have versions generated from a hash of their contents and the commit date, e.g. `18.3.0-canary-388686f29-20230503` for Canary and `0.0.0-experimental-388686f29-20230503` for Experimental.
**Both Latest and Canary channels are officially supported for user-facing applications, but with different expectations**:
- Latest releases follow the traditional semver model.
- Canary releases [must be pinned](https://react.dev/blog/2023/05/03/react-canaries) and may include breaking changes. They exist for curated setups (like frameworks) that want to gradually release new React features and bugfixes on their own release schedule.
The Experimental releases are provided for testing purposes only, and we provide no guarantees that behavior won’t change between releases. They do not follow the semver protocol that we use for releases from Latest.
By publishing prereleases to the same registry that we use for stable releases, we are able to take advantage of the many tools that support the npm workflow, like [unpkg](https://unpkg.com) and [CodeSandbox](https://codesandbox.io).
### Latest channel[Link for Latest channel]()
Latest is the channel used for stable React releases. It corresponds to the `latest` tag on npm. It is the recommended channel for all React apps that are shipped to real users.
**If you’re not sure which channel you should use, it’s Latest.** If you’re using React directly, this is what you’re already using. You can expect updates to Latest to be extremely stable. Versions follow the semantic versioning scheme, as [described earlier.]()
### Canary channel[Link for Canary channel]()
The Canary channel is a prerelease channel that tracks the main branch of the React repository. We use prereleases in the Canary channel as release candidates for the Latest channel. You can think of Canary as a superset of Latest that is updated more frequently.
The degree of change between the most recent Canary release and the most recent Latest release is approximately the same as you would find between two minor semver releases. However, **the Canary channel does not conform to semantic versioning.** You should expect occasional breaking changes between successive releases in the Canary channel.
**Do not use prereleases in user-facing applications directly unless you’re following the [Canary workflow](https://react.dev/blog/2023/05/03/react-canaries).**
Releases in Canary are published with the `canary` tag on npm. Versions are generated from a hash of the build’s contents and the commit date, e.g. `18.3.0-canary-388686f29-20230503`.
#### Using the canary channel for integration testing[Link for Using the canary channel for integration testing]()
The Canary channel also supports integration testing between React and other projects.
All changes to React go through extensive internal testing before they are released to the public. However, there are a myriad of environments and configurations used throughout the React ecosystem, and it’s not possible for us to test against every single one.
If you’re the author of a third party React framework, library, developer tool, or similar infrastructure-type project, you can help us keep React stable for your users and the entire React community by periodically running your test suite against the most recent changes. If you’re interested, follow these steps:
- Set up a cron job using your preferred continuous integration platform. Cron jobs are supported by both [CircleCI](https://circleci.com/docs/2.0/triggers/) and [Travis CI](https://docs.travis-ci.com/user/cron-jobs/).
- In the cron job, update your React packages to the most recent React release in the Canary channel, using `canary` tag on npm. Using the npm cli:
```
npm update react@canary react-dom@canary
```
Or yarn:
```
yarn upgrade react@canary react-dom@canary
```
- Run your test suite against the updated packages.
- If everything passes, great! You can expect that your project will work with the next minor React release.
- If something breaks unexpectedly, please let us know by [filing an issue](https://github.com/facebook/react/issues).
A project that uses this workflow is Next.js. You can refer to their [CircleCI configuration](https://github.com/zeit/next.js/blob/c0a1c0f93966fe33edd93fb53e5fafb0dcd80a9e/.circleci/config.yml) as an example.
### Experimental channel[Link for Experimental channel]()
Like Canary, the Experimental channel is a prerelease channel that tracks the main branch of the React repository. Unlike Canary, Experimental releases include additional features and APIs that are not ready for wider release.
Usually, an update to Canary is accompanied by a corresponding update to Experimental. They are based on the same source revision, but are built using a different set of feature flags.
Experimental releases may be significantly different than releases to Canary and Latest. **Do not use Experimental releases in user-facing applications.** You should expect frequent breaking changes between releases in the Experimental channel.
Releases in Experimental are published with the `experimental` tag on npm. Versions are generated from a hash of the build’s contents and the commit date, e.g. `0.0.0-experimental-68053d940-20210623`.
#### What goes into an experimental release?[Link for What goes into an experimental release?]()
Experimental features are ones that are not ready to be released to the wider public, and may change drastically before they are finalized. Some experiments may never be finalized — the reason we have experiments is to test the viability of proposed changes.
For example, if the Experimental channel had existed when we announced Hooks, we would have released Hooks to the Experimental channel weeks before they were available in Latest.
You may find it valuable to run integration tests against Experimental. This is up to you. However, be advised that Experimental is even less stable than Canary. **We do not guarantee any stability between Experimental releases.**
#### How can I learn more about experimental features?[Link for How can I learn more about experimental features?]()
Experimental features may or may not be documented. Usually, experiments aren’t documented until they are close to shipping in Canary or Latest.
If a feature is not documented, they may be accompanied by an [RFC](https://github.com/reactjs/rfcs).
We will post to the [React blog](https://react.dev/blog) when we’re ready to announce new experiments, but that doesn’t mean we will publicize every experiment.
You can always refer to our public GitHub repository’s [history](https://github.com/facebook/react/commits/main) for a comprehensive list of changes.
[PreviousAcknowledgements](https://react.dev/community/acknowledgements) |
https://react.dev/reference/react/hooks | [API Reference](https://react.dev/reference/react)
# Built-in React Hooks[Link for this heading]()
*Hooks* let you use different React features from your components. You can either use the built-in Hooks or combine them to build your own. This page lists all built-in Hooks in React.
* * *
## State Hooks[Link for State Hooks]()
*State* lets a component [“remember” information like user input.](https://react.dev/learn/state-a-components-memory) For example, a form component can use state to store the input value, while an image gallery component can use state to store the selected image index.
To add state to a component, use one of these Hooks:
- [`useState`](https://react.dev/reference/react/useState) declares a state variable that you can update directly.
- [`useReducer`](https://react.dev/reference/react/useReducer) declares a state variable with the update logic inside a [reducer function.](https://react.dev/learn/extracting-state-logic-into-a-reducer)
```
function ImageGallery() {
const [index, setIndex] = useState(0);
// ...
```
* * *
## Context Hooks[Link for Context Hooks]()
*Context* lets a component [receive information from distant parents without passing it as props.](https://react.dev/learn/passing-props-to-a-component) For example, your app’s top-level component can pass the current UI theme to all components below, no matter how deep.
- [`useContext`](https://react.dev/reference/react/useContext) reads and subscribes to a context.
```
function Button() {
const theme = useContext(ThemeContext);
// ...
```
* * *
## Ref Hooks[Link for Ref Hooks]()
*Refs* let a component [hold some information that isn’t used for rendering,](https://react.dev/learn/referencing-values-with-refs) like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an “escape hatch” from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.
- [`useRef`](https://react.dev/reference/react/useRef) declares a ref. You can hold any value in it, but most often it’s used to hold a DOM node.
- [`useImperativeHandle`](https://react.dev/reference/react/useImperativeHandle) lets you customize the ref exposed by your component. This is rarely used.
```
function Form() {
const inputRef = useRef(null);
// ...
```
* * *
## Effect Hooks[Link for Effect Hooks]()
*Effects* let a component [connect to and synchronize with external systems.](https://react.dev/learn/synchronizing-with-effects) This includes dealing with network, browser DOM, animations, widgets written using a different UI library, and other non-React code.
- [`useEffect`](https://react.dev/reference/react/useEffect) connects a component to an external system.
```
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
// ...
```
Effects are an “escape hatch” from the React paradigm. Don’t use Effects to orchestrate the data flow of your application. If you’re not interacting with an external system, [you might not need an Effect.](https://react.dev/learn/you-might-not-need-an-effect)
There are two rarely used variations of `useEffect` with differences in timing:
- [`useLayoutEffect`](https://react.dev/reference/react/useLayoutEffect) fires before the browser repaints the screen. You can measure layout here.
- [`useInsertionEffect`](https://react.dev/reference/react/useInsertionEffect) fires before React makes changes to the DOM. Libraries can insert dynamic CSS here.
* * *
## Performance Hooks[Link for Performance Hooks]()
A common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell React to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render.
To skip calculations and unnecessary re-rendering, use one of these Hooks:
- [`useMemo`](https://react.dev/reference/react/useMemo) lets you cache the result of an expensive calculation.
- [`useCallback`](https://react.dev/reference/react/useCallback) lets you cache a function definition before passing it down to an optimized component.
```
function TodoList({ todos, tab, theme }) {
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
// ...
}
```
Sometimes, you can’t skip re-rendering because the screen actually needs to update. In that case, you can improve performance by separating blocking updates that must be synchronous (like typing into an input) from non-blocking updates which don’t need to block the user interface (like updating a chart).
To prioritize rendering, use one of these Hooks:
- [`useTransition`](https://react.dev/reference/react/useTransition) lets you mark a state transition as non-blocking and allow other updates to interrupt it.
- [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue) lets you defer updating a non-critical part of the UI and let other parts update first.
* * *
## Other Hooks[Link for Other Hooks]()
These Hooks are mostly useful to library authors and aren’t commonly used in the application code.
- [`useDebugValue`](https://react.dev/reference/react/useDebugValue) lets you customize the label React DevTools displays for your custom Hook.
- [`useId`](https://react.dev/reference/react/useId) lets a component associate a unique ID with itself. Typically used with accessibility APIs.
- [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore) lets a component subscribe to an external store.
<!--THE END-->
- [`useActionState`](https://react.dev/reference/react/useActionState) allows you to manage state of actions.
* * *
## Your own Hooks[Link for Your own Hooks]()
You can also [define your own custom Hooks](https://react.dev/learn/reusing-logic-with-custom-hooks) as JavaScript functions.
[PreviousOverview](https://react.dev/reference/react)
[NextuseActionState](https://react.dev/reference/react/useActionState) |
https://react.dev/reference/react/useCallback | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useCallback[Link for this heading]()
`useCallback` is a React Hook that lets you cache a function definition between re-renders.
```
const cachedFn = useCallback(fn, dependencies)
```
- [Reference]()
- [`useCallback(fn, dependencies)`]()
- [Usage]()
- [Skipping re-rendering of components]()
- [Updating state from a memoized callback]()
- [Preventing an Effect from firing too often]()
- [Optimizing a custom Hook]()
- [Troubleshooting]()
- [Every time my component renders, `useCallback` returns a different function]()
- [I need to call `useCallback` for each list item in a loop, but it’s not allowed]()
* * *
## Reference[Link for Reference]()
### `useCallback(fn, dependencies)`[Link for this heading]()
Call `useCallback` at the top level of your component to cache a function definition between re-renders:
```
import { useCallback } from 'react';
export default function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `fn`: The function value that you want to cache. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. On next renders, React will give you the same function again if the `dependencies` have not changed since the last render. Otherwise, it will give you the function that you have passed during the current render, and store it in case it can be reused later. React will not call your function. The function is returned to you so you can decide when and whether to call it.
- `dependencies`: The list of all reactive values referenced inside of the `fn` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](https://react.dev/learn/editor-setup), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm.
#### Returns[Link for Returns]()
On the initial render, `useCallback` returns the `fn` function you have passed.
During subsequent renders, it will either return an already stored `fn` function from the last render (if the dependencies haven’t changed), or return the `fn` function you have passed during this render.
#### Caveats[Link for Caveats]()
- `useCallback` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
- React **will not throw away the cached function unless there is a specific reason to do that.** For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on `useCallback` as a performance optimization. Otherwise, a [state variable](https://react.dev/reference/react/useState) or a [ref](https://react.dev/reference/react/useRef) may be more appropriate.
* * *
## Usage[Link for Usage]()
### Skipping re-rendering of components[Link for Skipping re-rendering of components]()
When you optimize rendering performance, you will sometimes need to cache the functions that you pass to child components. Let’s first look at the syntax for how to do this, and then see in which cases it’s useful.
To cache a function between re-renders of your component, wrap its definition into the `useCallback` Hook:
```
import { useCallback } from 'react';
function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
// ...
```
You need to pass two things to `useCallback`:
1. A function definition that you want to cache between re-renders.
2. A list of dependencies including every value within your component that’s used inside your function.
On the initial render, the returned function you’ll get from `useCallback` will be the function you passed.
On the following renders, React will compare the dependencies with the dependencies you passed during the previous render. If none of the dependencies have changed (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), `useCallback` will return the same function as before. Otherwise, `useCallback` will return the function you passed on *this* render.
In other words, `useCallback` caches a function between re-renders until its dependencies change.
**Let’s walk through an example to see when this is useful.**
Say you’re passing a `handleSubmit` function down from the `ProductPage` to the `ShippingForm` component:
```
function ProductPage({ productId, referrer, theme }) {
// ...
return (
<div className={theme}>
<ShippingForm onSubmit={handleSubmit} />
</div>
);
```
You’ve noticed that toggling the `theme` prop freezes the app for a moment, but if you remove `<ShippingForm />` from your JSX, it feels fast. This tells you that it’s worth trying to optimize the `ShippingForm` component.
**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `ProductPage` re-renders with a different `theme`, the `ShippingForm` component *also* re-renders. This is fine for components that don’t require much calculation to re-render. But if you verified a re-render is slow, you can tell `ShippingForm` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](https://react.dev/reference/react/memo)
```
import { memo } from 'react';
const ShippingForm = memo(function ShippingForm({ onSubmit }) {
// ...
});
```
**With this change, `ShippingForm` will skip re-rendering if all of its props are the *same* as on the last render.** This is when caching a function becomes important! Let’s say you defined `handleSubmit` without `useCallback`:
```
function ProductPage({ productId, referrer, theme }) {
// Every time the theme changes, this will be a different function...
function handleSubmit(orderDetails) {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}
return (
<div className={theme}>
{/* ... so ShippingForm's props will never be the same, and it will re-render every time */}
<ShippingForm onSubmit={handleSubmit} />
</div>
);
}
```
**In JavaScript, a `function () {}` or `() => {}` always creates a *different* function,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn’t be a problem, but it means that `ShippingForm` props will never be the same, and your [`memo`](https://react.dev/reference/react/memo) optimization won’t work. This is where `useCallback` comes in handy:
```
function ProductPage({ productId, referrer, theme }) {
// Tell React to cache your function between re-renders...
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]); // ...so as long as these dependencies don't change...
return (
<div className={theme}>
{/* ...ShippingForm will receive the same props and can skip re-rendering */}
<ShippingForm onSubmit={handleSubmit} />
</div>
);
}
```
**By wrapping `handleSubmit` in `useCallback`, you ensure that it’s the *same* function between the re-renders** (until dependencies change). You don’t *have to* wrap a function in `useCallback` unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in [`memo`,](https://react.dev/reference/react/memo) and this lets it skip re-rendering. There are other reasons you might need `useCallback` which are described further on this page.
### Note
**You should only rely on `useCallback` as a performance optimization.** If your code doesn’t work without it, find the underlying problem and fix it first. Then you may add `useCallback` back.
##### Deep Dive
#### How is useCallback related to useMemo?[Link for How is useCallback related to useMemo?]()
Show Details
You will often see [`useMemo`](https://react.dev/reference/react/useMemo) alongside `useCallback`. They are both useful when you’re trying to optimize a child component. They let you [memoize](https://en.wikipedia.org/wiki/Memoization) (or, in other words, cache) something you’re passing down:
```
import { useMemo, useCallback } from 'react';
function ProductPage({ productId, referrer }) {
const product = useData('/product/' + productId);
const requirements = useMemo(() => { // Calls your function and caches its result
return computeRequirements(product);
}, [product]);
const handleSubmit = useCallback((orderDetails) => { // Caches your function itself
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
return (
<div className={theme}>
<ShippingForm requirements={requirements} onSubmit={handleSubmit} />
</div>
);
}
```
The difference is in *what* they’re letting you cache:
- **[`useMemo`](https://react.dev/reference/react/useMemo) caches the *result* of calling your function.** In this example, it caches the result of calling `computeRequirements(product)` so that it doesn’t change unless `product` has changed. This lets you pass the `requirements` object down without unnecessarily re-rendering `ShippingForm`. When necessary, React will call the function you’ve passed during rendering to calculate the result.
- **`useCallback` caches *the function itself.*** Unlike `useMemo`, it does not call the function you provide. Instead, it caches the function you provided so that `handleSubmit` *itself* doesn’t change unless `productId` or `referrer` has changed. This lets you pass the `handleSubmit` function down without unnecessarily re-rendering `ShippingForm`. Your code won’t run until the user submits the form.
If you’re already familiar with [`useMemo`,](https://react.dev/reference/react/useMemo) you might find it helpful to think of `useCallback` as this:
```
// Simplified implementation (inside React)
function useCallback(fn, dependencies) {
return useMemo(() => fn, dependencies);
}
```
[Read more about the difference between `useMemo` and `useCallback`.](https://react.dev/reference/react/useMemo)
##### Deep Dive
#### Should you add useCallback everywhere?[Link for Should you add useCallback everywhere?]()
Show Details
If your app is like this site, and most interactions are coarse (like replacing a page or an entire section), memoization is usually unnecessary. On the other hand, if your app is more like a drawing editor, and most interactions are granular (like moving shapes), then you might find memoization very helpful.
Caching a function with `useCallback` is only valuable in a few cases:
- You pass it as a prop to a component wrapped in [`memo`.](https://react.dev/reference/react/memo) You want to skip re-rendering if the value hasn’t changed. Memoization lets your component re-render only if dependencies changed.
- The function you’re passing is later used as a dependency of some Hook. For example, another function wrapped in `useCallback` depends on it, or you depend on this function from [`useEffect.`](https://react.dev/reference/react/useEffect)
There is no benefit to wrapping a function in `useCallback` in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside is that code becomes less readable. Also, not all memoization is effective: a single value that’s “always new” is enough to break memoization for an entire component.
Note that `useCallback` does not prevent *creating* the function. You’re always creating a function (and that’s fine!), but React ignores it and gives you back a cached function if nothing changed.
**In practice, you can make a lot of memoization unnecessary by following a few principles:**
1. When a component visually wraps other components, let it [accept JSX as children.](https://react.dev/learn/passing-props-to-a-component) Then, if the wrapper component updates its own state, React knows that its children don’t need to re-render.
2. Prefer local state and don’t [lift state up](https://react.dev/learn/sharing-state-between-components) any further than necessary. Don’t keep transient state like forms and whether an item is hovered at the top of your tree or in a global state library.
3. Keep your [rendering logic pure.](https://react.dev/learn/keeping-components-pure) If re-rendering a component causes a problem or produces some noticeable visual artifact, it’s a bug in your component! Fix the bug instead of adding memoization.
4. Avoid [unnecessary Effects that update state.](https://react.dev/learn/you-might-not-need-an-effect) Most performance problems in React apps are caused by chains of updates originating from Effects that cause your components to render over and over.
5. Try to [remove unnecessary dependencies from your Effects.](https://react.dev/learn/removing-effect-dependencies) For example, instead of memoization, it’s often simpler to move some object or a function inside an Effect or outside the component.
If a specific interaction still feels laggy, [use the React Developer Tools profiler](https://legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html) to see which components benefit the most from memoization, and add memoization where needed. These principles make your components easier to debug and understand, so it’s good to follow them in any case. In long term, we’re researching [doing memoization automatically](https://www.youtube.com/watch?v=lGEMwh32soc) to solve this once and for all.
#### The difference between useCallback and declaring a function directly[Link for The difference between useCallback and declaring a function directly]()
1\. Skipping re-rendering with `useCallback` and `memo` 2. Always re-rendering a component
#### Example 1 of 2: Skipping re-rendering with `useCallback` and `memo`[Link for this heading]()
In this example, the `ShippingForm` component is **artificially slowed down** so that you can see what happens when a React component you’re rendering is genuinely slow. Try incrementing the counter and toggling the theme.
Incrementing the counter feels slow because it forces the slowed down `ShippingForm` to re-render. That’s expected because the counter has changed, and so you need to reflect the user’s new choice on the screen.
Next, try toggling the theme. **Thanks to `useCallback` together with [`memo`](https://react.dev/reference/react/memo), it’s fast despite the artificial slowdown!** `ShippingForm` skipped re-rendering because the `handleSubmit` function has not changed. The `handleSubmit` function has not changed because both `productId` and `referrer` (your `useCallback` dependencies) haven’t changed since last render.
App.jsProductPage.jsShippingForm.js
ProductPage.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useCallback } from 'react';
import ShippingForm from './ShippingForm.js';
export default function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
return (
<div className={theme}>
<ShippingForm onSubmit={handleSubmit} />
</div>
);
}
function post(url, data) {
// Imagine this sends a request...
console.log('POST /' + url);
console.log(data);
}
```
Show more
Next Example
* * *
### Updating state from a memoized callback[Link for Updating state from a memoized callback]()
Sometimes, you might need to update state based on previous state from a memoized callback.
This `handleAddTodo` function specifies `todos` as a dependency because it computes the next todos from it:
```
function TodoList() {
const [todos, setTodos] = useState([]);
const handleAddTodo = useCallback((text) => {
const newTodo = { id: nextId++, text };
setTodos([...todos, newTodo]);
}, [todos]);
// ...
```
You’ll usually want memoized functions to have as few dependencies as possible. When you read some state only to calculate the next state, you can remove that dependency by passing an [updater function](https://react.dev/reference/react/useState) instead:
```
function TodoList() {
const [todos, setTodos] = useState([]);
const handleAddTodo = useCallback((text) => {
const newTodo = { id: nextId++, text };
setTodos(todos => [...todos, newTodo]);
}, []); // ✅ No need for the todos dependency
// ...
```
Here, instead of making `todos` a dependency and reading it inside, you pass an instruction about *how* to update the state (`todos => [...todos, newTodo]`) to React. [Read more about updater functions.](https://react.dev/reference/react/useState)
* * *
### Preventing an Effect from firing too often[Link for Preventing an Effect from firing too often]()
Sometimes, you might want to call a function from inside an [Effect:](https://react.dev/learn/synchronizing-with-effects)
```
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
function createOptions() {
return {
serverUrl: 'https://localhost:1234',
roomId: roomId
};
}
useEffect(() => {
const options = createOptions();
const connection = createConnection(options);
connection.connect();
// ...
```
This creates a problem. [Every reactive value must be declared as a dependency of your Effect.](https://react.dev/learn/lifecycle-of-reactive-effects) However, if you declare `createOptions` as a dependency, it will cause your Effect to constantly reconnect to the chat room:
```
useEffect(() => {
const options = createOptions();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [createOptions]); // 🔴 Problem: This dependency changes on every render
// ...
```
To solve this, you can wrap the function you need to call from an Effect into `useCallback`:
```
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const createOptions = useCallback(() => {
return {
serverUrl: 'https://localhost:1234',
roomId: roomId
};
}, [roomId]); // ✅ Only changes when roomId changes
useEffect(() => {
const options = createOptions();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [createOptions]); // ✅ Only changes when createOptions changes
// ...
```
This ensures that the `createOptions` function is the same between re-renders if the `roomId` is the same. **However, it’s even better to remove the need for a function dependency.** Move your function *inside* the Effect:
```
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
function createOptions() { // ✅ No need for useCallback or function dependencies!
return {
serverUrl: 'https://localhost:1234',
roomId: roomId
};
}
const options = createOptions();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ Only changes when roomId changes
// ...
```
Now your code is simpler and doesn’t need `useCallback`. [Learn more about removing Effect dependencies.](https://react.dev/learn/removing-effect-dependencies)
* * *
### Optimizing a custom Hook[Link for Optimizing a custom Hook]()
If you’re writing a [custom Hook,](https://react.dev/learn/reusing-logic-with-custom-hooks) it’s recommended to wrap any functions that it returns into `useCallback`:
```
function useRouter() {
const { dispatch } = useContext(RouterStateContext);
const navigate = useCallback((url) => {
dispatch({ type: 'navigate', url });
}, [dispatch]);
const goBack = useCallback(() => {
dispatch({ type: 'back' });
}, [dispatch]);
return {
navigate,
goBack,
};
}
```
This ensures that the consumers of your Hook can optimize their own code when needed.
* * *
## Troubleshooting[Link for Troubleshooting]()
### Every time my component renders, `useCallback` returns a different function[Link for this heading]()
Make sure you’ve specified the dependency array as a second argument!
If you forget the dependency array, `useCallback` will return a new function every time:
```
function ProductPage({ productId, referrer }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}); // 🔴 Returns a new function every time: no dependency array
// ...
```
This is the corrected version passing the dependency array as a second argument:
```
function ProductPage({ productId, referrer }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]); // ✅ Does not return a new function unnecessarily
// ...
```
If this doesn’t help, then the problem is that at least one of your dependencies is different from the previous render. You can debug this problem by manually logging your dependencies to the console:
```
const handleSubmit = useCallback((orderDetails) => {
// ..
}, [productId, referrer]);
console.log([productId, referrer]);
```
You can then right-click on the arrays from different re-renders in the console and select “Store as a global variable” for both of them. Assuming the first one got saved as `temp1` and the second one got saved as `temp2`, you can then use the browser console to check whether each dependency in both arrays is the same:
```
Object.is(temp1[0], temp2[0]); // Is the first dependency the same between the arrays?
Object.is(temp1[1], temp2[1]); // Is the second dependency the same between the arrays?
Object.is(temp1[2], temp2[2]); // ... and so on for every dependency ...
```
When you find which dependency is breaking memoization, either find a way to remove it, or [memoize it as well.](https://react.dev/reference/react/useMemo)
* * *
### I need to call `useCallback` for each list item in a loop, but it’s not allowed[Link for this heading]()
Suppose the `Chart` component is wrapped in [`memo`](https://react.dev/reference/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can’t call `useCallback` in a loop:
```
function ReportList({ items }) {
return (
<article>
{items.map(item => {
// 🔴 You can't call useCallback in a loop like this:
const handleClick = useCallback(() => {
sendReport(item)
}, [item]);
return (
<figure key={item.id}>
<Chart onClick={handleClick} />
</figure>
);
})}
</article>
);
}
```
Instead, extract a component for an individual item, and put `useCallback` there:
```
function ReportList({ items }) {
return (
<article>
{items.map(item =>
<Report key={item.id} item={item} />
)}
</article>
);
}
function Report({ item }) {
// ✅ Call useCallback at the top level:
const handleClick = useCallback(() => {
sendReport(item)
}, [item]);
return (
<figure>
<Chart onClick={handleClick} />
</figure>
);
}
```
Alternatively, you could remove `useCallback` in the last snippet and instead wrap `Report` itself in [`memo`.](https://react.dev/reference/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
```
function ReportList({ items }) {
// ...
}
const Report = memo(function Report({ item }) {
function handleClick() {
sendReport(item);
}
return (
<figure>
<Chart onClick={handleClick} />
</figure>
);
});
```
[PrevioususeActionState](https://react.dev/reference/react/useActionState)
[NextuseContext](https://react.dev/reference/react/useContext) |
https://react.dev/community/conferences | [Community](https://react.dev/community)
# React Conferences[Link for this heading]()
Do you know of a local React.js conference? Add it here! (Please keep the list chronological)
## Upcoming Conferences[Link for Upcoming Conferences]()
### React Day Berlin 2024[Link for React Day Berlin 2024]()
December 13 & 16, 2024. In-person in Berlin, Germany + remote (hybrid event)
[Website](https://reactday.berlin/) - [Twitter](https://x.com/reactdayberlin)
### App.js Conf 2025[Link for App.js Conf 2025]()
May 28 - 30, 2025. In-person in Kraków, Poland + remote
[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf)
### React Summit 2025[Link for React Summit 2025]()
June 13 - 17, 2025. In-person in Amsterdam, Netherlands + remote (hybrid event)
[Website](https://reactsummit.com/) - [Twitter](https://x.com/reactsummit)
## Past Conferences[Link for Past Conferences]()
### React Africa 2024[Link for React Africa 2024]()
November 29, 2024. In-person in Casablanca, Morocco (hybrid event)
[Website](https://react-africa.com/) - [Twitter](https://x.com/BeJS_)
### React Summit US 2024[Link for React Summit US 2024]()
November 19 & 22, 2024. In-person in New York, USA + online (hybrid event)
[Website](https://reactsummit.us/) - [Twitter](https://twitter.com/reactsummit) - [Videos](https://portal.gitnation.org/)
### React Native London Conf 2024[Link for React Native London Conf 2024]()
November 14 & 15, 2024. In-person in London, UK
[Website](https://reactnativelondon.co.uk/) - [Twitter](https://x.com/RNLConf)
### React Advanced London 2024[Link for React Advanced London 2024]()
October 25 & 28, 2024. In-person in London, UK + online (hybrid event)
[Website](https://reactadvanced.com/) - [Twitter](https://x.com/reactadvanced)
### reactjsday 2024[Link for reactjsday 2024]()
October 25, 2024. In-person in Verona, Italy + online (hybrid event)
[Website](https://2024.reactjsday.it/) - [Twitter](https://x.com/reactjsday) - [Facebook](https://www.facebook.com/GrUSP/) - [YouTube](https://www.youtube.com/c/grusp)
### React Brussels 2024[Link for React Brussels 2024]()
October 18, 2024. In-person in Brussels, Belgium (hybrid event)
[Website](https://www.react.brussels/) - [Twitter](https://x.com/BrusselsReact)
### React India 2024[Link for React India 2024]()
October 17 - 19, 2024. In-person in Goa, India (hybrid event) + Oct 15 2024 - remote day
[Website](https://www.reactindia.io) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia) - [Youtube](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w)
### RenderCon Kenya 2024[Link for RenderCon Kenya 2024]()
October 04 - 05, 2024. Nairobi, Kenya
[Website](https://rendercon.org/) - [Twitter](https://twitter.com/renderconke) - [LinkedIn](https://www.linkedin.com/company/renderconke/) - [YouTube](https://www.youtube.com/channel/UC0bCcG8gHUL4njDOpQGcMIA)
### React Alicante 2024[Link for React Alicante 2024]()
September 19-21, 2024. Alicante, Spain.
[Website](https://reactalicante.es/) - [Twitter](https://twitter.com/ReactAlicante) - [YouTube](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w)
### React Universe Conf 2024[Link for React Universe Conf 2024]()
September 5-6, 2024. Wrocław, Poland.
[Website](https://www.reactuniverseconf.com/) - [Twitter](https://twitter.com/react_native_eu) - [LinkedIn](https://www.linkedin.com/events/reactuniverseconf7163919537074118657/)
### React Rally 2024 🐙[Link for React Rally 2024 🐙]()
August 12-13, 2024. Park City, UT, USA
[Website](https://reactrally.com) - [Twitter](https://twitter.com/ReactRally) - [YouTube](https://www.youtube.com/channel/UCXBhQ05nu3L1abBUGeQ0ahw)
### The Geek Conf 2024[Link for The Geek Conf 2024]()
July 25, 2024. In-person in Berlin, Germany + remote (hybrid event)
[Website](https://thegeekconf.com) - [Twitter](https://twitter.com/thegeekconf)
### Chain React 2024[Link for Chain React 2024]()
July 17-19, 2024. In-person in Portland, OR, USA
[Website](https://chainreactconf.com) - [Twitter](https://twitter.com/ChainReactConf)
### React Nexus 2024[Link for React Nexus 2024]()
July 04 & 05, 2024. Bangalore, India (In-person event)
[Website](https://reactnexus.com/) - [Twitter](https://twitter.com/ReactNexus) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in)
### React Summit 2024[Link for React Summit 2024]()
June 14 & 18, 2024. In-person in Amsterdam, Netherlands + remote (hybrid event)
[Website](https://reactsummit.com/) - [Twitter](https://twitter.com/reactsummit) - [Videos](https://portal.gitnation.org/)
### React Norway 2024[Link for React Norway 2024]()
June 14, 2024. In-person at Farris Bad Hotel in Larvik, Norway and online (hybrid event).
[Website](https://reactnorway.com/) - [Twitter](https://twitter.com/ReactNorway)
### Render(ATL) 2024 🍑[Link for Render(ATL) 2024 🍑]()
June 12 - June 14, 2024. Atlanta, GA, USA
[Website](https://renderatl.com) - [Discord](https://www.renderatl.com/discord) - [Twitter](https://twitter.com/renderATL) - [Instagram](https://www.instagram.com/renderatl/) - [Facebook](https://www.facebook.com/renderatl/) - [LinkedIn](https://www.linkedin.com/company/renderatl) - [Podcast](https://www.renderatl.com/culture-and-code)
### Frontend Nation 2024[Link for Frontend Nation 2024]()
June 4 - 7, 2024. Online
[Website](https://frontendnation.com/) - [Twitter](https://twitter.com/frontendnation)
### App.js Conf 2024[Link for App.js Conf 2024]()
May 22 - 24, 2024. In-person in Kraków, Poland + remote
[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf)
### React Conf 2024[Link for React Conf 2024]()
May 15 - 16, 2024. In-person in Henderson, NV, USA + remote
[Website](https://conf.react.dev) - [Twitter](https://twitter.com/reactjs)
### React Native Connection 2024[Link for React Native Connection 2024]()
April 23, 2024. In-person in Paris, France
[Website](https://reactnativeconnection.io/) - [Twitter](https://twitter.com/ReactNativeConn)
### React Miami 2024[Link for React Miami 2024]()
April 19 - 20, 2024. In-person in Miami, FL, USA
[Website](https://reactmiami.com/) - [Twitter](https://twitter.com/ReactMiamiConf)
### Epic Web Conf 2024[Link for Epic Web Conf 2024]()
April 10 - 11, 2024. In-person in Park City, UT, USA
[Website](https://www.epicweb.dev/conf) - [YouTube](https://www.youtube.com/@EpicWebDev)
### React Paris 2024[Link for React Paris 2024]()
March 22, 2024. In-person in Paris, France + Remote (hybrid)
[Website](https://react.paris/) - [Twitter](https://twitter.com/BeJS_) - [LinkedIn](https://www.linkedin.com/events/7150816372074192900/comments/) - [Videos](https://www.youtube.com/playlist?list=PL53Z0yyYnpWhUzgvr2Nys3kZBBLcY0TA7)
### React Day Berlin 2023[Link for React Day Berlin 2023]()
December 8 & 12, 2023. In-person in Berlin, Germany + remote first interactivity (hybrid event)
[Website](https://reactday.berlin) - [Twitter](https://twitter.com/reactdayberlin) - [Facebook](https://www.facebook.com/reactdayberlin/) - [Videos](https://portal.gitnation.org/events/react-day-berlin-2023)
### React Summit US 2023[Link for React Summit US 2023]()
November 13 & 15, 2023. In-person in New York, US + remote first interactivity (hybrid event)
[Website](https://reactsummit.us) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://portal.gitnation.org/events/react-summit-us-2023)
### reactjsday 2023[Link for reactjsday 2023]()
October 27th 2023. In-person in Verona, Italy and online (hybrid event)
[Website](https://2023.reactjsday.it/) - [Twitter](https://twitter.com/reactjsday) - [Facebook](https://www.facebook.com/GrUSP/) - [YouTube](https://www.youtube.com/c/grusp)
### React Advanced 2023[Link for React Advanced 2023]()
October 20 & 23, 2023. In-person in London, UK + remote first interactivity (hybrid event)
[Website](https://www.reactadvanced.com/) - [Twitter](https://twitter.com/ReactAdvanced) - [Facebook](https://www.facebook.com/ReactAdvanced) - [Videos](https://portal.gitnation.org/events/react-advanced-conference-2023)
### React Brussels 2023[Link for React Brussels 2023]()
October 13th 2023. In-person in Brussels, Belgium + Remote (hybrid)
[Website](https://www.react.brussels/) - [Twitter](https://twitter.com/BrusselsReact) - [Videos](https://www.youtube.com/playlist?list=PL53Z0yyYnpWh85KeMomUoVz8_brrmh_aC)
### React India 2023[Link for React India 2023]()
October 5 - 7, 2023. In-person in Goa, India (hybrid event) + Oct 3 2023 - remote day
[Website](https://www.reactindia.io) - [Twitter](https://x.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia) - [Youtube](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w)
### RenderCon Kenya 2023[Link for RenderCon Kenya 2023]()
September 29 - 30, 2023. Nairobi, Kenya
[Website](https://rendercon.org/) - [Twitter](https://twitter.com/renderconke) - [LinkedIn](https://www.linkedin.com/company/renderconke/) - [YouTube](https://www.youtube.com/channel/UC0bCcG8gHUL4njDOpQGcMIA)
### React Live 2023[Link for React Live 2023]()
September 29, 2023. Amsterdam, Netherlands
[Website](https://reactlive.nl/)
### React Alicante 2023[Link for React Alicante 2023]()
September 28 - 30, 2023. Alicante, Spain
[Website](https://reactalicante.es/) - [Twitter](https://twitter.com/reactalicante)
### RedwoodJS Conference 2023[Link for RedwoodJS Conference 2023]()
September 26 - 29, 2023. Grants Pass, Oregon + remote (hybrid event)
[Website](https://www.redwoodjsconf.com/) - [Twitter](https://twitter.com/redwoodjs)
### React Native EU 2023[Link for React Native EU 2023]()
September 7 & 8, 2023. Wrocław, Poland
[Website](https://react-native.eu) - [Twitter](https://twitter.com/react_native_eu) - [Facebook](https://www.facebook.com/reactnativeeu)
### React Rally 2023 🐙[Link for React Rally 2023 🐙]()
August 17 & 18, 2023. Salt Lake City, UT, USA
[Website](https://www.reactrally.com/) - [Twitter](https://twitter.com/ReactRally) - [Instagram](https://www.instagram.com/reactrally/)
### React Nexus 2023[Link for React Nexus 2023]()
July 07 & 08, 2023. Bangalore, India (In-person event)
[Website](https://reactnexus.com/) - [Twitter](https://twitter.com/ReactNexus) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in)
### ReactNext 2023[Link for ReactNext 2023]()
June 27th, 2023. Tel Aviv, Israel
[Website](https://www.react-next.com/) - [Facebook](https://www.facebook.com/ReactNextConf) - [Youtube](https://www.youtube.com/@ReactNext)
### React Norway 2023[Link for React Norway 2023]()
June 16th, 2023. Larvik, Norway
[Website](https://reactnorway.com/) - [Twitter](https://twitter.com/ReactNorway/) - [Facebook](https://www.facebook.com/reactdaynorway/)
### React Summit 2023[Link for React Summit 2023]()
June 2 & 6, 2023. In-person in Amsterdam, Netherlands + remote first interactivity (hybrid event)
[Website](https://reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://portal.gitnation.org/events/react-summit-2023)
### Render(ATL) 2023 🍑[Link for Render(ATL) 2023 🍑]()
May 31 - June 2, 2023. Atlanta, GA, USA
[Website](https://renderatl.com) - [Discord](https://www.renderatl.com/discord) - [Twitter](https://twitter.com/renderATL) - [Instagram](https://www.instagram.com/renderatl/) - [Facebook](https://www.facebook.com/renderatl/) - [LinkedIn](https://www.linkedin.com/company/renderatl) - [Podcast](https://www.renderatl.com/culture-and-code)
### Chain React 2023[Link for Chain React 2023]()
May 17 - 19, 2023. Portland, OR, USA
[Website](https://chainreactconf.com/) - [Twitter](https://twitter.com/ChainReactConf) - [Facebook](https://www.facebook.com/ChainReactConf/) - [Youtube](https://www.youtube.com/channel/UCwpSzVt7QpLDbCnPXqR97-g/playlists)
### App.js Conf 2023[Link for App.js Conf 2023]()
May 10 - 12, 2023. In-person in Kraków, Poland + remote
[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf)
### RemixConf 2023[Link for RemixConf 2023]()
May, 2023. Salt Lake City, UT
[Website](https://remix.run/conf/2023) - [Twitter](https://twitter.com/remix_run)
### Reactathon 2023[Link for Reactathon 2023]()
May 2 - 3, 2023. San Francisco, CA, USA
[Website](https://reactathon.com) - [Twitter](https://twitter.com/reactathon) - [YouTube](https://www.youtube.com/realworldreact)
### React Miami 2023[Link for React Miami 2023]()
April 20 - 21, 2023. Miami, FL, USA
[Website](https://www.reactmiami.com/) - [Twitter](https://twitter.com/ReactMiamiConf)
### React Day Berlin 2022[Link for React Day Berlin 2022]()
December 2, 2022. In-person in Berlin, Germany + remote (hybrid event)
[Website](https://reactday.berlin) - [Twitter](https://twitter.com/reactdayberlin) - [Facebook](https://www.facebook.com/reactdayberlin/) - [Videos](https://www.youtube.com/c/ReactConferences)
### React Global Online Summit 22.2 by Geekle[Link for React Global Online Summit 22.2 by Geekle]()
November 8 - 9, 2022 - Online Summit
[Website](https://events.geekle.us/react3/) - [LinkedIn](https://www.linkedin.com/posts/geekle-us_event-react-reactjs-activity-6964904611207864320-gpDx?utm_source=share&utm_medium=member_desktop)
### Remix Conf Europe 2022[Link for Remix Conf Europe 2022]()
November 18, 2022, 7am PST / 10am EST / 4pm CET - remote event
[Website](https://remixconf.eu/) - [Twitter](https://twitter.com/remixconfeu) - [Videos](https://portal.gitnation.org/events/remix-conf-europe-2022)
### React Advanced 2022[Link for React Advanced 2022]()
October 21 & 25, 2022. In-person in London, UK + remote (hybrid event)
[Website](https://www.reactadvanced.com/) - [Twitter](https://twitter.com/ReactAdvanced) - [Facebook](https://www.facebook.com/ReactAdvanced) - [Videos](https://portal.gitnation.org/events/react-advanced-conference-2022)
### ReactJS Day 2022[Link for ReactJS Day 2022]()
October 21, 2022 in Verona, Italy
[Website](https://2022.reactjsday.it/) - [Twitter](https://twitter.com/reactjsday) - [LinkedIn](https://www.linkedin.com/company/grusp/) - [Facebook](https://www.facebook.com/reactjsday/) - [Videos](https://www.youtube.com/c/grusp)
### React Brussels 2022[Link for React Brussels 2022]()
October 14, 2022. In-person in Brussels, Belgium + remote (hybrid event)
[Website](https://www.react.brussels/) - [Twitter](https://twitter.com/BrusselsReact) - [LinkedIn](https://www.linkedin.com/events/6938421827153088512/) - [Facebook](https://www.facebook.com/events/1289080838167252/) - [Videos](https://www.youtube.com/channel/UCvES7lMpnx-t934qGxD4w4g)
### React Alicante 2022[Link for React Alicante 2022]()
September 29 - October 1, 2022. In-person in Alicante, Spain + remote (hybrid event)
[Website](https://reactalicante.es/) - [Twitter](https://twitter.com/reactalicante) - [Facebook](https://www.facebook.com/ReactAlicante) - [Videos](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w)
### React India 2022[Link for React India 2022]()
September 22 - 24, 2022. In-person in Goa, India + remote (hybrid event)
[Website](https://www.reactindia.io) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia) - [Videos](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w)
### React Finland 2022[Link for React Finland 2022]()
September 12 - 16, 2022. In-person in Helsinki, Finland
[Website](https://react-finland.fi/) - [Twitter](https://twitter.com/ReactFinland) - [Schedule](https://react-finland.fi/schedule/) - [Speakers](https://react-finland.fi/speakers/)
### React Native EU 2022: Powered by callstack[Link for React Native EU 2022: Powered by callstack]()
September 1-2, 2022 - Remote event
[Website](https://www.react-native.eu/?utm_campaign=React_Native_EU&utm_source=referral&utm_content=reactjs_community_conferences) - [Twitter](https://twitter.com/react_native_eu) - [Linkedin](https://www.linkedin.com/showcase/react-native-eu) - [Facebook](https://www.facebook.com/reactnativeeu/) - [Instagram](https://www.instagram.com/reactnative_eu/)
### ReactNext 2022[Link for ReactNext 2022]()
June 28, 2022. Tel-Aviv, Israel
[Website](https://react-next.com) - [Twitter](https://twitter.com/ReactNext) - [Videos](https://www.youtube.com/c/ReactNext)
### React Norway 2022[Link for React Norway 2022]()
June 24, 2022. In-person at Farris Bad Hotel in Larvik, Norway and online (hybrid event).
[Website](https://reactnorway.com/) - [Twitter](https://twitter.com/ReactNorway)
### React Summit 2022[Link for React Summit 2022]()
June 17 & 21, 2022. In-person in Amsterdam, Netherlands + remote first interactivity (hybrid event)
[Website](https://reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://portal.gitnation.org/events/react-summit-2022)
### App.js Conf 2022[Link for App.js Conf 2022]()
June 8 - 10, 2022. In-person in Kraków, Poland + remote
[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf)
### React Day Bangalore 2022[Link for React Day Bangalore 2022]()
June 8 - 9, 2022. Remote
[Website](https://reactday.in/) - [Twitter](https://twitter.com/ReactDayIn) - [Linkedin](https://www.linkedin.com/company/react-day/) - [YouTube](https://www.youtube.com/reactify_in)
### render(ATL) 2022 🍑[Link for render(ATL) 2022 🍑]()
June 1 - 4, 2022. Atlanta, GA, USA
[Website](https://renderatl.com) - [Discord](https://www.renderatl.com/discord) - [Twitter](https://twitter.com/renderATL) - [Instagram](https://www.instagram.com/renderatl/) - [Facebook](https://www.facebook.com/renderatl/) - [LinkedIn](https://www.linkedin.com/company/renderatl) - [Podcast](https://www.renderatl.com/culture-and-code)
### RemixConf 2022[Link for RemixConf 2022]()
May 24 - 25, 2022. Salt Lake City, UT
[Website](https://remix.run/conf/2022) - [Twitter](https://twitter.com/remix_run) - [YouTube](https://www.youtube.com/playlist?list=PLXoynULbYuEC36XutMMWEuTu9uuh171wx)
### Reactathon 2022[Link for Reactathon 2022]()
May 3 - 5, 2022. Berkeley, CA
[Website](https://reactathon.com) - [Twitter](https://twitter.com/reactathon) -[YouTube](https://www.youtube.com/watch?v=-YG5cljNXIA)
### React Global Online Summit 2022 by Geekle[Link for React Global Online Summit 2022 by Geekle]()
April 20 - 21, 2022 - Online Summit
[Website](https://events.geekle.us/react2/) - [LinkedIn](https://www.linkedin.com/events/reactglobalonlinesummit-226887417664541614081/)
### React Miami 2022 🌴[Link for React Miami 2022 🌴]()
April 18 - 19, 2022. Miami, Florida [Website](https://www.reactmiami.com/)
### React Live 2022[Link for React Live 2022]()
April 1, 2022. Amsterdam, The Netherlands
[Website](https://www.reactlive.nl/) - [Twitter](https://twitter.com/reactlivenl)
### AgentConf 2022[Link for AgentConf 2022]()
January 27 - 30, 2022. In-person in Dornbirn and Lech Austria
[Website](https://agent.sh/) - [Twitter](https://twitter.com/AgentConf) - [Instagram](https://www.instagram.com/teamagent/)
### React Conf 2021[Link for React Conf 2021]()
December 8, 2021 - remote event (replay event on December 9)
[Website](https://conf.reactjs.org/)
### ReactEurope 2021[Link for ReactEurope 2021]()
December 9-10, 2021 - remote event
[Videos](https://www.youtube.com/c/ReacteuropeOrgConf)
### ReactNext 2021[Link for ReactNext 2021]()
December 15, 2021. Tel-Aviv, Israel
[Website](https://react-next.com) - [Twitter](https://twitter.com/ReactNext) - [Videos](https://www.youtube.com/channel/UC3BT8hh3yTTYxbLQy_wbk2w)
### React India 2021[Link for React India 2021]()
November 12-13, 2021 - remote event
[Website](https://www.reactindia.io) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia/) - [LinkedIn](https://www.linkedin.com/showcase/14545585) - [YouTube](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w/videos)
### React Global by Geekle[Link for React Global by Geekle]()
November 3-4, 2021 - remote event
[Website](https://geekle.us/react) - [LinkedIn](https://www.linkedin.com/events/javascriptglobalsummit6721691514176720896/) - [YouTube](https://www.youtube.com/watch?v=0HhWIvPhbu0)
### React Advanced 2021[Link for React Advanced 2021]()
October 22-23, 2021. In-person in London, UK + remote (hybrid event)
[Website](https://reactadvanced.com) - [Twitter](https://twitter.com/reactadvanced) - [Facebook](https://www.facebook.com/ReactAdvanced) - [Videos](https://youtube.com/c/ReactConferences)
### React Conf Brasil 2021[Link for React Conf Brasil 2021]()
October 16, 2021 - remote event
[Website](http://reactconf.com.br) - [Twitter](https://twitter.com/reactconfbr) - [Slack](https://react.now.sh) - [Facebook](https://facebook.com/reactconf) - [Instagram](https://instagram.com/reactconfbr) - [YouTube](https://www.youtube.com/channel/UCJL5eorStQfC0x1iiWhvqPA/videos)
### React Brussels 2021[Link for React Brussels 2021]()
October 15, 2021 - remote event
[Website](https://www.react.brussels/) - [Twitter](https://twitter.com/BrusselsReact) - [LinkedIn](https://www.linkedin.com/events/6805708233819336704/)
### render(ATL) 2021[Link for render(ATL) 2021]()
September 13-15, 2021. Atlanta, GA, USA
[Website](https://renderatl.com) - [Twitter](https://twitter.com/renderATL) - [Instagram](https://www.instagram.com/renderatl/) - [Facebook](https://www.facebook.com/renderatl/) - [LinkedIn](https://www.linkedin.com/company/renderatl)
### React Native EU 2021[Link for React Native EU 2021]()
September 1-2, 2021 - remote event
[Website](https://www.react-native.eu/) - [Twitter](https://twitter.com/react_native_eu) - [Facebook](https://www.facebook.com/reactnativeeu/) - [Instagram](https://www.instagram.com/reactnative_eu/)
### React Finland 2021[Link for React Finland 2021]()
August 30 - September 3, 2021 - remote event
[Website](https://react-finland.fi/) - [Twitter](https://twitter.com/ReactFinland) - [LinkedIn](https://www.linkedin.com/company/react-finland/)
### React Case Study Festival 2021[Link for React Case Study Festival 2021]()
April 27-28, 2021 - remote event
[Website](https://link.geekle.us/react/offsite) - [LinkedIn](https://www.linkedin.com/events/reactcasestudyfestival6721300943411015680/) - [Facebook](https://www.facebook.com/events/255715435820203)
### React Summit - Remote Edition 2021[Link for React Summit - Remote Edition 2021]()
April 14-16, 2021, 7am PST / 10am EST / 4pm CEST - remote event
[Website](https://remote.reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://portal.gitnation.org/events/react-summit-remote-edition-2021)
### React fwdays’21[Link for React fwdays’21]()
March 27, 2021 - remote event
[Website](https://fwdays.com/en/event/react-fwdays-2021) - [Twitter](https://twitter.com/fwdays) - [Facebook](https://www.facebook.com/events/1133828147054286) - [LinkedIn](https://www.linkedin.com/events/reactfwdays-21onlineconference6758046347334582273) - [Meetup](https://www.meetup.com/ru-RU/Fwdays/events/275764431/)
### React Next 2020[Link for React Next 2020]()
December 1-2, 2020 - remote event
[Website](https://react-next.com/) - [Twitter](https://twitter.com/reactnext) - [Facebook](https://www.facebook.com/ReactNext2016/)
### React Conf Brasil 2020[Link for React Conf Brasil 2020]()
November 21, 2020 - remote event
[Website](https://reactconf.com.br/) - [Twitter](https://twitter.com/reactconfbr) - [Slack](https://react.now.sh/)
### React Summit 2020[Link for React Summit 2020]()
October 15-16, 2020, 7am PST / 10am EST / 4pm CEST - remote event
[Website](https://reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://youtube.com/c/ReactConferences)
### React Native EU 2020[Link for React Native EU 2020]()
September 3-4, 2020 - remote event
[Website](https://www.react-native.eu/) - [Twitter](https://twitter.com/react_native_eu) - [Facebook](https://www.facebook.com/reactnativeeu/) - [YouTube](https://www.youtube.com/watch?v=m0GfmlGFh3E&list=PLZ3MwD-soTTHy9_88QPLF8DEJkvoB5Tl-) - [Instagram](https://www.instagram.com/reactnative_eu/)
### ReactEurope 2020[Link for ReactEurope 2020]()
May 14-15, 2020 in Paris, France
[Videos](https://www.youtube.com/c/ReacteuropeOrgConf)
### Byteconf React 2020[Link for Byteconf React 2020]()
May 1, 2020. Streamed online on YouTube.
[Website](https://www.bytesized.xyz) - [Twitter](https://twitter.com/bytesizedcode) - [YouTube](https://www.youtube.com/channel/UC046lFvJZhiwSRWsoH8SFjg)
### React Summit - Remote Edition 2020[Link for React Summit - Remote Edition 2020]()
3pm CEST time, April 17, 2020 - remote event
[Website](https://remote.reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://youtube.com/c/ReactConferences)
### Reactathon 2020[Link for Reactathon 2020]()
March 30 - 31, 2020 in San Francisco, CA
[Website](https://www.reactathon.com) - [Twitter](https://twitter.com/reactathon) - [Facebook](https://www.facebook.com/events/575942819854160/)
### ReactConf AU 2020[Link for ReactConf AU 2020]()
February 27 & 28, 2020 in Sydney, Australia
[Website](https://reactconfau.com/) - [Twitter](https://twitter.com/reactconfau) - [Facebook](https://www.facebook.com/reactconfau) - [Instagram](https://www.instagram.com/reactconfau/)
### React Barcamp Cologne 2020[Link for React Barcamp Cologne 2020]()
February 1-2, 2020 in Cologne, Germany
[Website](https://react-barcamp.de/) - [Twitter](https://twitter.com/ReactBarcamp) - [Facebook](https://www.facebook.com/reactbarcamp)
### React Day Berlin 2019[Link for React Day Berlin 2019]()
December 6, 2019 in Berlin, Germany
[Website](https://reactday.berlin) - [Twitter](https://twitter.com/reactdayberlin) - [Facebook](https://www.facebook.com/reactdayberlin/) - [Videos](https://www.youtube.com/reactdayberlin)
### React Summit 2019[Link for React Summit 2019]()
November 30, 2019 in Lagos, Nigeria
[Website](https://reactsummit2019.splashthat.com) -[Twitter](https://twitter.com/react_summit)
### React Conf Brasil 2019[Link for React Conf Brasil 2019]()
October 19, 2019 in São Paulo, BR
[Website](https://reactconf.com.br/) - [Twitter](https://twitter.com/reactconfbr) - [Facebook](https://www.facebook.com/ReactAdvanced) - [Slack](https://react.now.sh/)
### React Advanced 2019[Link for React Advanced 2019]()
October 25, 2019 in London, UK
[Website](https://reactadvanced.com) - [Twitter](http://twitter.com/reactadvanced) - [Facebook](https://www.facebook.com/ReactAdvanced) - [Videos](https://youtube.com/c/ReactConferences)
### React Conf 2019[Link for React Conf 2019]()
October 24-25, 2019 in Henderson, Nevada USA
[Website](https://conf.reactjs.org/) - [Twitter](https://twitter.com/reactjs)
### React Alicante 2019[Link for React Alicante 2019]()
September 26-28, 2019 in Alicante, Spain
[Website](http://reactalicante.es/) - [Twitter](https://twitter.com/reactalicante) - [Facebook](https://www.facebook.com/ReactAlicante)
### React India 2019[Link for React India 2019]()
September 26-28, 2019 in Goa, India
[Website](https://www.reactindia.io/) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia)
### React Boston 2019[Link for React Boston 2019]()
September 21-22, 2019 in Boston, Massachusetts USA
[Website](https://www.reactboston.com/) - [Twitter](https://twitter.com/reactboston)
### React Live 2019[Link for React Live 2019]()
September 13th, 2019. Amsterdam, The Netherlands
[Website](https://www.reactlive.nl/) - [Twitter](https://twitter.com/reactlivenl)
### React New York 2019[Link for React New York 2019]()
September 13th, 2019. New York, USA
[Website](https://reactnewyork.com/) - [Twitter](https://twitter.com/reactnewyork)
### ComponentsConf 2019[Link for ComponentsConf 2019]()
September 6, 2019 in Melbourne, Australia
[Website](https://www.componentsconf.com.au/) - [Twitter](https://twitter.com/componentsconf)
### React Native EU 2019[Link for React Native EU 2019]()
September 5-6 in Wrocław, Poland
[Website](https://react-native.eu) - [Twitter](https://twitter.com/react_native_eu) - [Facebook](https://www.facebook.com/reactnativeeu)
### React Conf Iran 2019[Link for React Conf Iran 2019]()
August 29, 2019. Tehran, Iran.
[Website](https://reactconf.ir/) - [Videos](https://www.youtube.com/playlist?list=PL-VNqZFI5Nf-Nsj0rD3CWXGPkH-DI_0VY) - [Highlights](https://github.com/ReactConf/react-conf-highlights)
### React Rally 2019[Link for React Rally 2019]()
August 22-23, 2019. Salt Lake City, USA.
[Website](https://www.reactrally.com/) - [Twitter](https://twitter.com/ReactRally) - [Instagram](https://www.instagram.com/reactrally/)
### Chain React 2019[Link for Chain React 2019]()
July 11-12, 2019. Portland, OR, USA.
[Website](https://infinite.red/ChainReactConf)
### React Loop 2019[Link for React Loop 2019]()
June 21, 2019 Chicago, Illinois USA
[Website](https://reactloop.com) - [Twitter](https://twitter.com/ReactLoop)
### React Norway 2019[Link for React Norway 2019]()
June 12, 2019. Larvik, Norway
[Website](https://reactnorway.com) - [Twitter](https://twitter.com/ReactNorway)
### ReactNext 2019[Link for ReactNext 2019]()
June 11, 2019. Tel Aviv, Israel
[Website](https://react-next.com) - [Twitter](https://twitter.com/ReactNext) - [Videos](https://www.youtube.com/channel/UC3BT8hh3yTTYxbLQy_wbk2w)
### React Conf Armenia 2019[Link for React Conf Armenia 2019]()
May 25, 2019 in Yerevan, Armenia
[Website](https://reactconf.am/) - [Twitter](https://twitter.com/ReactConfAM) - [Facebook](https://www.facebook.com/reactconf.am/) - [YouTube](https://www.youtube.com/c/JavaScriptConferenceArmenia) - [CFP](http://bit.ly/speakReact)
### ReactEurope 2019[Link for ReactEurope 2019]()
May 23-24, 2019 in Paris, France
[Videos](https://www.youtube.com/c/ReacteuropeOrgConf)
### React.NotAConf 2019[Link for React.NotAConf 2019]()
May 11 in Sofia, Bulgaria
[Website](http://react-not-a-conf.com/) - [Twitter](https://twitter.com/reactnotaconf) - [Facebook](https://www.facebook.com/events/780891358936156)
### ReactJS Girls Conference[Link for ReactJS Girls Conference]()
May 3, 2019 in London, UK
[Website](https://reactjsgirls.com/) - [Twitter](https://twitter.com/reactjsgirls)
### React Finland 2019[Link for React Finland 2019]()
April 24-26 in Helsinki, Finland
[Website](https://react-finland.fi/) - [Twitter](https://twitter.com/ReactFinland)
### React Amsterdam 2019[Link for React Amsterdam 2019]()
April 12, 2019 in Amsterdam, The Netherlands
[Website](https://reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://youtube.com/c/ReactConferences)
### App.js Conf 2019[Link for App.js Conf 2019]()
April 4-5, 2019 in Kraków, Poland
[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf)
### Reactathon 2019[Link for Reactathon 2019]()
March 30-31, 2019 in San Francisco, USA
[Website](https://www.reactathon.com/) - [Twitter](https://twitter.com/reactathon)
### React Iran 2019[Link for React Iran 2019]()
January 31, 2019 in Tehran, Iran
[Website](http://reactiran.com) - [Instagram](https://www.instagram.com/reactiran/)
### React Day Berlin 2018[Link for React Day Berlin 2018]()
November 30, Berlin, Germany
[Website](https://reactday.berlin) - [Twitter](https://twitter.com/reactdayberlin) - [Facebook](https://www.facebook.com/reactdayberlin/) - [Videos](https://www.youtube.com/channel/UC1EYHmQYBUJjkmL6OtK4rlw)
### ReactNext 2018[Link for ReactNext 2018]()
November 4 in Tel Aviv, Israel
[Website](https://react-next.com) - [Twitter](https://twitter.com/ReactNext) - [Facebook](https://facebook.com/ReactNext2016)
### React Conf 2018[Link for React Conf 2018]()
October 25-26 in Henderson, Nevada USA
[Website](https://conf.reactjs.org/)
### React Conf Brasil 2018[Link for React Conf Brasil 2018]()
October 20 in Sao Paulo, Brazil
[Website](http://reactconfbr.com.br) - [Twitter](https://twitter.com/reactconfbr) - [Facebook](https://www.facebook.com/reactconf)
### ReactJS Day 2018[Link for ReactJS Day 2018]()
October 5 in Verona, Italy
[Website](http://2018.reactjsday.it) - [Twitter](https://twitter.com/reactjsday)
### React Boston 2018[Link for React Boston 2018]()
September 29-30 in Boston, Massachusetts USA
[Website](http://www.reactboston.com/) - [Twitter](https://twitter.com/ReactBoston)
### React Alicante 2018[Link for React Alicante 2018]()
September 13-15 in Alicante, Spain
[Website](http://reactalicante.es) - [Twitter](https://twitter.com/ReactAlicante)
### React Native EU 2018[Link for React Native EU 2018]()
September 5-6 in Wrocław, Poland
[Website](https://react-native.eu) - [Twitter](https://twitter.com/react_native_eu) - [Facebook](https://www.facebook.com/reactnativeeu)
### Byteconf React 2018[Link for Byteconf React 2018]()
August 31 streamed online, via Twitch
[Website](https://byteconf.com) - [Twitch](https://twitch.tv/byteconf) - [Twitter](https://twitter.com/byteconf)
### ReactFoo Delhi[Link for ReactFoo Delhi]()
August 18 in Delhi, India
[Website](https://reactfoo.in/2018-delhi/) - [Twitter](https://twitter.com/reactfoo) - [Past talks](https://hasgeek.tv)
### React DEV Conf China[Link for React DEV Conf China]()
August 18 in Guangzhou, China
[Website](https://react.w3ctech.com)
### React Rally 2018[Link for React Rally 2018]()
August 16-17 in Salt Lake City, Utah USA
[Website](http://www.reactrally.com) - [Twitter](https://twitter.com/reactrally)
### Chain React 2018[Link for Chain React 2018]()
July 11-13 in Portland, Oregon USA
[Website](https://infinite.red/ChainReactConf) - [Twitter](https://twitter.com/chainreactconf)
### ReactFoo Mumbai[Link for ReactFoo Mumbai]()
May 26 in Mumbai, India
[Website](https://reactfoo.in/2018-mumbai/) - [Twitter](https://twitter.com/reactfoo) - [Past talks](https://hasgeek.tv)
### ReactEurope 2018[Link for ReactEurope 2018]()
May 17-18 in Paris, France
[Videos](https://www.youtube.com/c/ReacteuropeOrgConf)
### React.NotAConf 2018[Link for React.NotAConf 2018]()
April 28 in Sofia, Bulgaria
[Website](http://react-not-a-conf.com/) - [Twitter](https://twitter.com/reactnotaconf) - [Facebook](https://www.facebook.com/groups/1614950305478021/)
### React Finland 2018[Link for React Finland 2018]()
April 24-26 in Helsinki, Finland
[Website](https://react-finland.fi/) - [Twitter](https://twitter.com/ReactFinland)
### React Amsterdam 2018[Link for React Amsterdam 2018]()
April 13 in Amsterdam, The Netherlands
[Website](https://reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam)
### React Native Camp UA 2018[Link for React Native Camp UA 2018]()
March 31 in Kiev, Ukraine
[Website](http://reactnative.com.ua/) - [Twitter](https://twitter.com/reactnativecamp) - [Facebook](https://www.facebook.com/reactnativecamp/)
### Reactathon 2018[Link for Reactathon 2018]()
March 20-22 in San Francisco, USA
[Website](https://www.reactathon.com/) - [Twitter](https://twitter.com/reactathon) - [Videos (fundamentals)](https://www.youtube.com/watch?v=knn364bssQU&list=PLRvKvw42Rc7OWK5s-YGGFSmByDzzgC0HP), [Videos (advanced day1)](https://www.youtube.com/watch?v=57hmk4GvJpk&list=PLRvKvw42Rc7N0QpX2Rc5CdrqGuxzwD_0H), [Videos (advanced day2)](https://www.youtube.com/watch?v=1hvQ8p8q0a0&list=PLRvKvw42Rc7Ne46QAjWNWFo1Jf0mQdnIW)
### ReactFest 2018[Link for ReactFest 2018]()
March 8-9 in London, UK
[Website](https://reactfest.uk/) - [Twitter](https://twitter.com/ReactFest) - [Videos](https://www.youtube.com/watch?v=YOCrJ5vRCnw&list=PLRgweB8YtNRt-Sf-A0y446wTJNUaAAmle)
### AgentConf 2018[Link for AgentConf 2018]()
January 25-28 in Dornbirn, Austria
[Website](http://agent.sh/)
### ReactFoo Pune[Link for ReactFoo Pune]()
January 19-20, Pune, India
[Website](https://reactfoo.in/2018-pune/) - [Twitter](https://twitter.com/ReactFoo)
### React Day Berlin 2017[Link for React Day Berlin 2017]()
December 2, Berlin, Germany
[Website](https://reactday.berlin) - [Twitter](https://twitter.com/reactdayberlin) - [Facebook](https://www.facebook.com/reactdayberlin/) - [Videos](https://www.youtube.com/watch?v=UnNLJvHKfSY&list=PL-3BrJ5CiIx5GoXci54-VsrO6GwLhSHEK)
### React Seoul 2017[Link for React Seoul 2017]()
November 4 in Seoul, South Korea
[Website](http://seoul.reactjs.kr/en)
### ReactiveConf 2017[Link for ReactiveConf 2017]()
October 25–27, Bratislava, Slovakia
[Website](https://reactiveconf.com) - [Videos](https://www.youtube.com/watch?v=BOKxSFB2hOE&list=PLa2ZZ09WYepMB-I7AiDjDYR8TjO8uoNjs)
### React Summit 2017[Link for React Summit 2017]()
October 21 in Lagos, Nigeria
[Website](https://reactsummit2017.splashthat.com/) - [Twitter](https://twitter.com/DevCircleLagos/) - [Facebook](https://www.facebook.com/groups/DevCLagos/)
### State.js Conference 2017[Link for State.js Conference 2017]()
October 13 in Stockholm, Sweden
[Website](https://statejs.com/)
### React Conf Brasil 2017[Link for React Conf Brasil 2017]()
October 7 in Sao Paulo, Brazil
[Website](http://reactconfbr.com.br) - [Twitter](https://twitter.com/reactconfbr) - [Facebook](https://www.facebook.com/reactconf/)
### ReactJS Day 2017[Link for ReactJS Day 2017]()
October 6 in Verona, Italy
[Website](http://2017.reactjsday.it) - [Twitter](https://twitter.com/reactjsday) - [Videos](https://www.youtube.com/watch?v=bUqqJPIgjNU&list=PLWK9j6ps_unl293VhhN4RYMCISxye3xH9)
### React Alicante 2017[Link for React Alicante 2017]()
September 28-30 in Alicante, Spain
[Website](http://reactalicante.es) - [Twitter](https://twitter.com/ReactAlicante) - [Videos](https://www.youtube.com/watch?v=UMZvRCWo6Dw&list=PLd7nkr8mN0sWvBH_s0foCE6eZTX8BmLUM)
### React Boston 2017[Link for React Boston 2017]()
September 23-24 in Boston, Massachusetts USA
[Website](http://www.reactboston.com/) - [Twitter](https://twitter.com/ReactBoston) - [Videos](https://www.youtube.com/watch?v=2iPE5l3cl_s&list=PL-fCkV3wv4ub8zJMIhmrrLcQqSR5XPlIT)
### ReactFoo 2017[Link for ReactFoo 2017]()
September 14 in Bangalore, India
[Website](https://reactfoo.in/2017/) - [Videos](https://www.youtube.com/watch?v=3G6tMg29Wnw&list=PL279M8GbNsespKKm1L0NAzYLO6gU5LvfH)
### ReactNext 2017[Link for ReactNext 2017]()
September 8-10 in Tel Aviv, Israel
[Website](http://react-next.com/) - [Twitter](https://twitter.com/ReactNext) - [Videos (Hall A)](https://www.youtube.com/watch?v=eKXQw5kR86c&list=PLMYVq3z1QxSqq6D7jxVdqttOX7H_Brq8Z), [Videos (Hall B)](https://www.youtube.com/watch?v=1InokWxYGnE&list=PLMYVq3z1QxSqCZmaqgTXLsrcJ8mZmBF7T)
### React Native EU 2017[Link for React Native EU 2017]()
September 6-7 in Wroclaw, Poland
[Website](http://react-native.eu/) - [Videos](https://www.youtube.com/watch?v=453oKJAqfy0&list=PLzUKC1ci01h_hkn7_KoFA-Au0DXLAQZR7)
### React Rally 2017[Link for React Rally 2017]()
August 24-25 in Salt Lake City, Utah USA
[Website](http://www.reactrally.com) - [Twitter](https://twitter.com/reactrally) - [Videos](https://www.youtube.com/watch?v=f4KnHNCZcH4&list=PLUD4kD-wL_zZUhvAIHJjueJDPr6qHvkni)
### Chain React 2017[Link for Chain React 2017]()
July 10-11 in Portland, Oregon USA
[Website](https://infinite.red/ChainReactConf) - [Twitter](https://twitter.com/chainreactconf) - [Videos](https://www.youtube.com/watch?v=cz5BzwgATpc&list=PLFHvL21g9bk3RxJ1Ut5nR_uTZFVOxu522)
### ReactEurope 2017[Link for ReactEurope 2017]()
May 18th & 19th in Paris, France
[Videos](https://www.youtube.com/c/ReacteuropeOrgConf)
### React Amsterdam 2017[Link for React Amsterdam 2017]()
April 21st in Amsterdam, The Netherlands
[Website](https://reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Videos](https://youtube.com/c/ReactConferences)
### React London 2017[Link for React London 2017]()
March 28th at the [QEII Centre, London](http://qeiicentre.london/)
[Website](http://react.london/) - [Videos](https://www.youtube.com/watch?v=2j9rSur_mnk&list=PLW6ORi0XZU0CFjdoYeC0f5QReBG-NeNKJ)
### React Conf 2017[Link for React Conf 2017]()
March 13-14 in Santa Clara, CA
[Website](http://conf.reactjs.org/) - [Videos](https://www.youtube.com/watch?v=7HSd1sk07uU&list=PLb0IAmt7-GS3fZ46IGFirdqKTIxlws7e0)
### Agent Conference 2017[Link for Agent Conference 2017]()
January 20-21 in Dornbirn, Austria
[Website](http://agent.sh/)
### React Remote Conf 2016[Link for React Remote Conf 2016]()
October 26-28 online
[Website](https://allremoteconfs.com/react-2016) - [Schedule](https://allremoteconfs.com/react-2016)
### Reactive 2016[Link for Reactive 2016]()
October 26-28 in Bratislava, Slovakia
[Website](https://reactiveconf.com/)
### ReactNL 2016[Link for ReactNL 2016]()
October 13 in Amsterdam, The Netherlands
[Website](http://reactnl.org/) - [Schedule](http://reactnl.org/)
### ReactNext 2016[Link for ReactNext 2016]()
September 15 in Tel Aviv, Israel
[Website](http://react-next.com/) - [Schedule](http://react-next.com/) - [Videos](https://www.youtube.com/channel/UC3BT8hh3yTTYxbLQy_wbk2w)
### ReactRally 2016[Link for ReactRally 2016]()
August 25-26 in Salt Lake City, UT
[Website](http://www.reactrally.com/) - [Schedule](http://www.reactrally.com/) - [Videos](https://www.youtube.com/playlist?list=PLUD4kD-wL_zYSfU3tIYsb4WqfFQzO_EjQ)
### ReactEurope 2016[Link for ReactEurope 2016]()
June 2 & 3 in Paris, France
[Videos](https://www.youtube.com/c/ReacteuropeOrgConf)
### React Amsterdam 2016[Link for React Amsterdam 2016]()
April 16 in Amsterdam, The Netherlands
[Website](https://reactsummit.com) - [Twitter](https://twitter.com/reactsummit) - [Facebook](https://www.facebook.com/reactamsterdam) - [Videos](https://youtube.com/c/ReactConferences)
### React.js Conf 2016[Link for React.js Conf 2016]()
February 22 & 23 in San Francisco, CA
[Website](http://conf2016.reactjs.org/) - [Schedule](http://conf2016.reactjs.org/schedule.html) - [Videos](https://www.youtube.com/playlist?list=PLb0IAmt7-GS0M8Q95RIc2lOM6nc77q1IY)
### Reactive 2015[Link for Reactive 2015]()
November 2-4 in Bratislava, Slovakia
[Website](https://reactive2015.com/) - [Schedule](https://reactive2015.com/schedule_speakers.html)
### ReactEurope 2015[Link for ReactEurope 2015]()
July 2 & 3 in Paris, France
[Videos](https://www.youtube.com/c/ReacteuropeOrgConf)
### React.js Conf 2015[Link for React.js Conf 2015]()
January 28 & 29 in Facebook HQ, CA
[Website](http://conf2015.reactjs.org/) - [Schedule](http://conf2015.reactjs.org/schedule.html) - [Videos](https://www.youtube.com/playlist?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr)
[PreviousCommunity](https://react.dev/community)
[NextReact Meetups](https://react.dev/community/meetups) |
https://react.dev/reference/react/useDebugValue | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useDebugValue[Link for this heading]()
`useDebugValue` is a React Hook that lets you add a label to a custom Hook in [React DevTools.](https://react.dev/learn/react-developer-tools)
```
useDebugValue(value, format?)
```
- [Reference]()
- [`useDebugValue(value, format?)`]()
- [Usage]()
- [Adding a label to a custom Hook]()
- [Deferring formatting of a debug value]()
* * *
## Reference[Link for Reference]()
### `useDebugValue(value, format?)`[Link for this heading]()
Call `useDebugValue` at the top level of your [custom Hook](https://react.dev/learn/reusing-logic-with-custom-hooks) to display a readable debug value:
```
import { useDebugValue } from 'react';
function useOnlineStatus() {
// ...
useDebugValue(isOnline ? 'Online' : 'Offline');
// ...
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `value`: The value you want to display in React DevTools. It can have any type.
- **optional** `format`: A formatting function. When the component is inspected, React DevTools will call the formatting function with the `value` as the argument, and then display the returned formatted value (which may have any type). If you don’t specify the formatting function, the original `value` itself will be displayed.
#### Returns[Link for Returns]()
`useDebugValue` does not return anything.
## Usage[Link for Usage]()
### Adding a label to a custom Hook[Link for Adding a label to a custom Hook]()
Call `useDebugValue` at the top level of your [custom Hook](https://react.dev/learn/reusing-logic-with-custom-hooks) to display a readable debug value for [React DevTools.](https://react.dev/learn/react-developer-tools)
```
import { useDebugValue } from 'react';
function useOnlineStatus() {
// ...
useDebugValue(isOnline ? 'Online' : 'Offline');
// ...
}
```
This gives components calling `useOnlineStatus` a label like `OnlineStatus: "Online"` when you inspect them:
![A screenshot of React DevTools showing the debug value](/images/docs/react-devtools-usedebugvalue.png)
Without the `useDebugValue` call, only the underlying data (in this example, `true`) would be displayed.
App.jsuseOnlineStatus.js
useOnlineStatus.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useSyncExternalStore, useDebugValue } from 'react';
export function useOnlineStatus() {
const isOnline = useSyncExternalStore(subscribe, () => navigator.onLine, () => true);
useDebugValue(isOnline ? 'Online' : 'Offline');
return isOnline;
}
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
```
Show more
### Note
Don’t add debug values to every custom Hook. It’s most valuable for custom Hooks that are part of shared libraries and that have a complex internal data structure that’s difficult to inspect.
* * *
### Deferring formatting of a debug value[Link for Deferring formatting of a debug value]()
You can also pass a formatting function as the second argument to `useDebugValue`:
```
useDebugValue(date, date => date.toDateString());
```
Your formatting function will receive the debug value as a parameter and should return a formatted display value. When your component is inspected, React DevTools will call this function and display its result.
This lets you avoid running potentially expensive formatting logic unless the component is actually inspected. For example, if `date` is a Date value, this avoids calling `toDateString()` on it for every render.
[PrevioususeContext](https://react.dev/reference/react/useContext)
[NextuseDeferredValue](https://react.dev/reference/react/useDeferredValue) |
https://react.dev/reference/react/useDeferredValue | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useDeferredValue[Link for this heading]()
`useDeferredValue` is a React Hook that lets you defer updating a part of the UI.
```
const deferredValue = useDeferredValue(value)
```
- [Reference]()
- [`useDeferredValue(value, initialValue?)`]()
- [Usage]()
- [Showing stale content while fresh content is loading]()
- [Indicating that the content is stale]()
- [Deferring re-rendering for a part of the UI]()
* * *
## Reference[Link for Reference]()
### `useDeferredValue(value, initialValue?)`[Link for this heading]()
Call `useDeferredValue` at the top level of your component to get a deferred version of that value.
```
import { useState, useDeferredValue } from 'react';
function SearchPage() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
// ...
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `value`: The value you want to defer. It can have any type.
- **optional** `initialValue`: A value to use during the initial render of a component. If this option is omitted, `useDeferredValue` will not defer during the initial render, because there’s no previous version of `value` that it can render instead.
#### Returns[Link for Returns]()
- `currentValue`: During the initial render, the returned deferred value will be the `initialValue`, or the same as the value you provided. During updates, React will first attempt a re-render with the old value (so it will return the old value), and then try another re-render in the background with the new value (so it will return the updated value).
#### Caveats[Link for Caveats]()
- When an update is inside a Transition, `useDeferredValue` always returns the new `value` and does not spawn a deferred render, since the update is already deferred.
- The values you pass to `useDeferredValue` should either be primitive values (like strings and numbers) or objects created outside of rendering. If you create a new object during rendering and immediately pass it to `useDeferredValue`, it will be different on every render, causing unnecessary background re-renders.
- When `useDeferredValue` receives a different value (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), in addition to the current render (when it still uses the previous value), it schedules a re-render in the background with the new value. The background re-render is interruptible: if there’s another update to the `value`, React will restart the background re-render from scratch. For example, if the user is typing into an input faster than a chart receiving its deferred value can re-render, the chart will only re-render after the user stops typing.
- `useDeferredValue` is integrated with [`<Suspense>`.](https://react.dev/reference/react/Suspense) If the background update caused by a new value suspends the UI, the user will not see the fallback. They will see the old deferred value until the data loads.
- `useDeferredValue` does not by itself prevent extra network requests.
- There is no fixed delay caused by `useDeferredValue` itself. As soon as React finishes the original re-render, React will immediately start working on the background re-render with the new deferred value. Any updates caused by events (like typing) will interrupt the background re-render and get prioritized over it.
- The background re-render caused by `useDeferredValue` does not fire Effects until it’s committed to the screen. If the background re-render suspends, its Effects will run after the data loads and the UI updates.
* * *
## Usage[Link for Usage]()
### Showing stale content while fresh content is loading[Link for Showing stale content while fresh content is loading]()
Call `useDeferredValue` at the top level of your component to defer updating some part of your UI.
```
import { useState, useDeferredValue } from 'react';
function SearchPage() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
// ...
}
```
During the initial render, the deferred value will be the same as the value you provided.
During updates, the deferred value will “lag behind” the latest value. In particular, React will first re-render *without* updating the deferred value, and then try to re-render with the newly received value in the background.
**Let’s walk through an example to see when this is useful.**
### Note
This example assumes you use a Suspense-enabled data source:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/getting-started/react-essentials)
- Lazy-loading component code with [`lazy`](https://react.dev/reference/react/lazy)
- Reading the value of a Promise with [`use`](https://react.dev/reference/react/use)
[Learn more about Suspense and its limitations.](https://react.dev/reference/react/Suspense)
In this example, the `SearchResults` component [suspends](https://react.dev/reference/react/Suspense) while fetching the search results. Try typing `"a"`, waiting for the results, and then editing it to `"ab"`. The results for `"a"` get replaced by the loading fallback.
App.jsSearchResults.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState } from 'react';
import SearchResults from './SearchResults.js';
export default function App() {
const [query, setQuery] = useState('');
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<SearchResults query={query} />
</Suspense>
</>
);
}
```
Show more
A common alternative UI pattern is to *defer* updating the list of results and to keep showing the previous results until the new results are ready. Call `useDeferredValue` to pass a deferred version of the query down:
```
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<SearchResults query={deferredQuery} />
</Suspense>
</>
);
}
```
The `query` will update immediately, so the input will display the new value. However, the `deferredQuery` will keep its previous value until the data has loaded, so `SearchResults` will show the stale results for a bit.
Enter `"a"` in the example below, wait for the results to load, and then edit the input to `"ab"`. Notice how instead of the Suspense fallback, you now see the stale result list until the new results have loaded:
App.jsSearchResults.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState, useDeferredValue } from 'react';
import SearchResults from './SearchResults.js';
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<SearchResults query={deferredQuery} />
</Suspense>
</>
);
}
```
Show more
##### Deep Dive
#### How does deferring a value work under the hood?[Link for How does deferring a value work under the hood?]()
Show Details
You can think of it as happening in two steps:
1. **First, React re-renders with the new `query` (`"ab"`) but with the old `deferredQuery` (still `"a")`.** The `deferredQuery` value, which you pass to the result list, is *deferred:* it “lags behind” the `query` value.
2. **In the background, React tries to re-render with *both* `query` and `deferredQuery` updated to `"ab"`.** If this re-render completes, React will show it on the screen. However, if it suspends (the results for `"ab"` have not loaded yet), React will abandon this rendering attempt, and retry this re-render again after the data has loaded. The user will keep seeing the stale deferred value until the data is ready.
The deferred “background” rendering is interruptible. For example, if you type into the input again, React will abandon it and restart with the new value. React will always use the latest provided value.
Note that there is still a network request per each keystroke. What’s being deferred here is displaying results (until they’re ready), not the network requests themselves. Even if the user continues typing, responses for each keystroke get cached, so pressing Backspace is instant and doesn’t fetch again.
* * *
### Indicating that the content is stale[Link for Indicating that the content is stale]()
In the example above, there is no indication that the result list for the latest query is still loading. This can be confusing to the user if the new results take a while to load. To make it more obvious to the user that the result list does not match the latest query, you can add a visual indication when the stale result list is displayed:
```
<div style={{
opacity: query !== deferredQuery ? 0.5 : 1,
}}>
<SearchResults query={deferredQuery} />
</div>
```
With this change, as soon as you start typing, the stale result list gets slightly dimmed until the new result list loads. You can also add a CSS transition to delay dimming so that it feels gradual, like in the example below:
App.jsSearchResults.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState, useDeferredValue } from 'react';
import SearchResults from './SearchResults.js';
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<div style={{
opacity: isStale ? 0.5 : 1,
transition: isStale ? 'opacity 0.2s 0.2s linear' : 'opacity 0s 0s linear'
}}>
<SearchResults query={deferredQuery} />
</div>
</Suspense>
</>
);
}
```
Show more
* * *
### Deferring re-rendering for a part of the UI[Link for Deferring re-rendering for a part of the UI]()
You can also apply `useDeferredValue` as a performance optimization. It is useful when a part of your UI is slow to re-render, there’s no easy way to optimize it, and you want to prevent it from blocking the rest of the UI.
Imagine you have a text field and a component (like a chart or a long list) that re-renders on every keystroke:
```
function App() {
const [text, setText] = useState('');
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<SlowList text={text} />
</>
);
}
```
First, optimize `SlowList` to skip re-rendering when its props are the same. To do this, [wrap it in `memo`:](https://react.dev/reference/react/memo)
```
const SlowList = memo(function SlowList({ text }) {
// ...
});
```
However, this only helps if the `SlowList` props are *the same* as during the previous render. The problem you’re facing now is that it’s slow when they’re *different,* and when you actually need to show different visual output.
Concretely, the main performance problem is that whenever you type into the input, the `SlowList` receives new props, and re-rendering its entire tree makes the typing feel janky. In this case, `useDeferredValue` lets you prioritize updating the input (which must be fast) over updating the result list (which is allowed to be slower):
```
function App() {
const [text, setText] = useState('');
const deferredText = useDeferredValue(text);
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<SlowList text={deferredText} />
</>
);
}
```
This does not make re-rendering of the `SlowList` faster. However, it tells React that re-rendering the list can be deprioritized so that it doesn’t block the keystrokes. The list will “lag behind” the input and then “catch up”. Like before, React will attempt to update the list as soon as possible, but will not block the user from typing.
#### The difference between useDeferredValue and unoptimized re-rendering[Link for The difference between useDeferredValue and unoptimized re-rendering]()
1\. Deferred re-rendering of the list 2. Unoptimized re-rendering of the list
#### Example 1 of 2: Deferred re-rendering of the list[Link for this heading]()
In this example, each item in the `SlowList` component is **artificially slowed down** so that you can see how `useDeferredValue` lets you keep the input responsive. Type into the input and notice that typing feels snappy while the list “lags behind” it.
App.jsSlowList.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useDeferredValue } from 'react';
import SlowList from './SlowList.js';
export default function App() {
const [text, setText] = useState('');
const deferredText = useDeferredValue(text);
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<SlowList text={deferredText} />
</>
);
}
```
Next Example
### Pitfall
This optimization requires `SlowList` to be wrapped in [`memo`.](https://react.dev/reference/react/memo) This is because whenever the `text` changes, React needs to be able to re-render the parent component quickly. During that re-render, `deferredText` still has its previous value, so `SlowList` is able to skip re-rendering (its props have not changed). Without [`memo`,](https://react.dev/reference/react/memo) it would have to re-render anyway, defeating the point of the optimization.
##### Deep Dive
#### How is deferring a value different from debouncing and throttling?[Link for How is deferring a value different from debouncing and throttling?]()
Show Details
There are two common optimization techniques you might have used before in this scenario:
- *Debouncing* means you’d wait for the user to stop typing (e.g. for a second) before updating the list.
- *Throttling* means you’d update the list every once in a while (e.g. at most once a second).
While these techniques are helpful in some cases, `useDeferredValue` is better suited to optimizing rendering because it is deeply integrated with React itself and adapts to the user’s device.
Unlike debouncing or throttling, it doesn’t require choosing any fixed delay. If the user’s device is fast (e.g. powerful laptop), the deferred re-render would happen almost immediately and wouldn’t be noticeable. If the user’s device is slow, the list would “lag behind” the input proportionally to how slow the device is.
Also, unlike with debouncing or throttling, deferred re-renders done by `useDeferredValue` are interruptible by default. This means that if React is in the middle of re-rendering a large list, but the user makes another keystroke, React will abandon that re-render, handle the keystroke, and then start rendering in the background again. By contrast, debouncing and throttling still produce a janky experience because they’re *blocking:* they merely postpone the moment when rendering blocks the keystroke.
If the work you’re optimizing doesn’t happen during rendering, debouncing and throttling are still useful. For example, they can let you fire fewer network requests. You can also use these techniques together.
[PrevioususeDebugValue](https://react.dev/reference/react/useDebugValue)
[NextuseEffect](https://react.dev/reference/react/useEffect) |
https://react.dev/reference/react/useContext | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useContext[Link for this heading]()
`useContext` is a React Hook that lets you read and subscribe to [context](https://react.dev/learn/passing-data-deeply-with-context) from your component.
```
const value = useContext(SomeContext)
```
- [Reference]()
- [`useContext(SomeContext)`]()
- [Usage]()
- [Passing data deeply into the tree]()
- [Updating data passed via context]()
- [Specifying a fallback default value]()
- [Overriding context for a part of the tree]()
- [Optimizing re-renders when passing objects and functions]()
- [Troubleshooting]()
- [My component doesn’t see the value from my provider]()
- [I am always getting `undefined` from my context although the default value is different]()
* * *
## Reference[Link for Reference]()
### `useContext(SomeContext)`[Link for this heading]()
Call `useContext` at the top level of your component to read and subscribe to [context.](https://react.dev/learn/passing-data-deeply-with-context)
```
import { useContext } from 'react';
function MyComponent() {
const theme = useContext(ThemeContext);
// ...
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `SomeContext`: The context that you’ve previously created with [`createContext`](https://react.dev/reference/react/createContext). The context itself does not hold the information, it only represents the kind of information you can provide or read from components.
#### Returns[Link for Returns]()
`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](https://react.dev/reference/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.
#### Caveats[Link for Caveats]()
- `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `<Context.Provider>` **needs to be *above*** the component doing the `useContext()` call.
- React **automatically re-renders** all the children that use a particular context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](https://react.dev/reference/react/memo) does not prevent the children receiving fresh context values.
- If your build system produces duplicates modules in the output (which can happen with symlinks), this can break context. Passing something via context only works if `SomeContext` that you use to provide context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison.
* * *
## Usage[Link for Usage]()
### Passing data deeply into the tree[Link for Passing data deeply into the tree]()
Call `useContext` at the top level of your component to read and subscribe to [context.](https://react.dev/learn/passing-data-deeply-with-context)
```
import { useContext } from 'react';
function Button() {
const theme = useContext(ThemeContext);
// ...
```
`useContext` returns the context value for the context you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context.
To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider:
```
function MyPage() {
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>
);
}
function Form() {
// ... renders buttons inside ...
}
```
It doesn’t matter how many layers of components there are between the provider and the `Button`. When a `Button` *anywhere* inside of `Form` calls `useContext(ThemeContext)`, it will receive `"dark"` as the value.
### Pitfall
`useContext()` always looks for the closest provider *above* the component that calls it. It searches upwards and **does not** consider providers in the component from which you’re calling `useContext()`.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createContext, useContext } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() {
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>
)
}
function Form() {
return (
<Panel title="Welcome">
<Button>Sign up</Button>
<Button>Log in</Button>
</Panel>
);
}
function Panel({ title, children }) {
const theme = useContext(ThemeContext);
const className = 'panel-' + theme;
return (
<section className={className}>
<h1>{title}</h1>
{children}
</section>
)
}
function Button({ children }) {
const theme = useContext(ThemeContext);
const className = 'button-' + theme;
return (
<button className={className}>
{children}
</button>
);
}
```
Show more
* * *
### Updating data passed via context[Link for Updating data passed via context]()
Often, you’ll want the context to change over time. To update context, combine it with [state.](https://react.dev/reference/react/useState) Declare a state variable in the parent component, and pass the current state down as the context value to the provider.
```
function MyPage() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext.Provider value={theme}>
<Form />
<Button onClick={() => {
setTheme('light');
}}>
Switch to light theme
</Button>
</ThemeContext.Provider>
);
}
```
Now any `Button` inside of the provider will receive the current `theme` value. If you call `setTheme` to update the `theme` value that you pass to the provider, all `Button` components will re-render with the new `'light'` value.
#### Examples of updating context[Link for Examples of updating context]()
1\. Updating a value via context 2. Updating an object via context 3. Multiple contexts 4. Extracting providers to a component 5. Scaling up with context and a reducer
#### Example 1 of 5: Updating a value via context[Link for this heading]()
In this example, the `MyApp` component holds a state variable which is then passed to the `ThemeContext` provider. Checking the “Dark mode” checkbox updates the state. Changing the provided value re-renders all the components using that context.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<Form />
<label>
<input
type="checkbox"
checked={theme === 'dark'}
onChange={(e) => {
setTheme(e.target.checked ? 'dark' : 'light')
}}
/>
Use dark mode
</label>
</ThemeContext.Provider>
)
}
function Form({ children }) {
return (
<Panel title="Welcome">
<Button>Sign up</Button>
<Button>Log in</Button>
</Panel>
);
}
function Panel({ title, children }) {
const theme = useContext(ThemeContext);
const className = 'panel-' + theme;
return (
<section className={className}>
<h1>{title}</h1>
{children}
</section>
)
}
function Button({ children }) {
const theme = useContext(ThemeContext);
const className = 'button-' + theme;
return (
<button className={className}>
{children}
</button>
);
}
```
Show more
Note that `value="dark"` passes the `"dark"` string, but `value={theme}` passes the value of the JavaScript `theme` variable with [JSX curly braces.](https://react.dev/learn/javascript-in-jsx-with-curly-braces) Curly braces also let you pass context values that aren’t strings.
Next Example
* * *
### Specifying a fallback default value[Link for Specifying a fallback default value]()
If React can’t find any providers of that particular context in the parent tree, the context value returned by `useContext()` will be equal to the default value that you specified when you [created that context](https://react.dev/reference/react/createContext):
```
const ThemeContext = createContext(null);
```
The default value **never changes**. If you want to update context, use it with state as [described above.]()
Often, instead of `null`, there is some more meaningful value you can use as a default, for example:
```
const ThemeContext = createContext('light');
```
This way, if you accidentally render some component without a corresponding provider, it won’t break. This also helps your components work well in a test environment without setting up a lot of providers in the tests.
In the example below, the “Toggle theme” button is always light because it’s **outside any theme context provider** and the default context theme value is `'light'`. Try editing the default theme to be `'dark'`.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
export default function MyApp() {
const [theme, setTheme] = useState('light');
return (
<>
<ThemeContext.Provider value={theme}>
<Form />
</ThemeContext.Provider>
<Button onClick={() => {
setTheme(theme === 'dark' ? 'light' : 'dark');
}}>
Toggle theme
</Button>
</>
)
}
function Form({ children }) {
return (
<Panel title="Welcome">
<Button>Sign up</Button>
<Button>Log in</Button>
</Panel>
);
}
function Panel({ title, children }) {
const theme = useContext(ThemeContext);
const className = 'panel-' + theme;
return (
<section className={className}>
<h1>{title}</h1>
{children}
</section>
)
}
function Button({ children, onClick }) {
const theme = useContext(ThemeContext);
const className = 'button-' + theme;
return (
<button className={className} onClick={onClick}>
{children}
</button>
);
}
```
Show more
* * *
### Overriding context for a part of the tree[Link for Overriding context for a part of the tree]()
You can override the context for a part of the tree by wrapping that part in a provider with a different value.
```
<ThemeContext.Provider value="dark">
...
<ThemeContext.Provider value="light">
<Footer />
</ThemeContext.Provider>
...
</ThemeContext.Provider>
```
You can nest and override providers as many times as you need.
#### Examples of overriding context[Link for Examples of overriding context]()
1\. Overriding a theme 2. Automatically nested headings
#### Example 1 of 2: Overriding a theme[Link for this heading]()
Here, the button *inside* the `Footer` receives a different context value (`"light"`) than the buttons outside (`"dark"`).
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createContext, useContext } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() {
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>
)
}
function Form() {
return (
<Panel title="Welcome">
<Button>Sign up</Button>
<Button>Log in</Button>
<ThemeContext.Provider value="light">
<Footer />
</ThemeContext.Provider>
</Panel>
);
}
function Footer() {
return (
<footer>
<Button>Settings</Button>
</footer>
);
}
function Panel({ title, children }) {
const theme = useContext(ThemeContext);
const className = 'panel-' + theme;
return (
<section className={className}>
{title && <h1>{title}</h1>}
{children}
</section>
)
}
function Button({ children }) {
const theme = useContext(ThemeContext);
const className = 'button-' + theme;
return (
<button className={className}>
{children}
</button>
);
}
```
Show more
Next Example
* * *
### Optimizing re-renders when passing objects and functions[Link for Optimizing re-renders when passing objects and functions]()
You can pass any values via context, including objects and functions.
```
function MyApp() {
const [currentUser, setCurrentUser] = useState(null);
function login(response) {
storeCredentials(response.credentials);
setCurrentUser(response.user);
}
return (
<AuthContext.Provider value={{ currentUser, login }}>
<Page />
</AuthContext.Provider>
);
}
```
Here, the context value is a JavaScript object with two properties, one of which is a function. Whenever `MyApp` re-renders (for example, on a route update), this will be a *different* object pointing at a *different* function, so React will also have to re-render all components deep in the tree that call `useContext(AuthContext)`.
In smaller apps, this is not a problem. However, there is no need to re-render them if the underlying data, like `currentUser`, has not changed. To help React take advantage of that fact, you may wrap the `login` function with [`useCallback`](https://react.dev/reference/react/useCallback) and wrap the object creation into [`useMemo`](https://react.dev/reference/react/useMemo). This is a performance optimization:
```
import { useCallback, useMemo } from 'react';
function MyApp() {
const [currentUser, setCurrentUser] = useState(null);
const login = useCallback((response) => {
storeCredentials(response.credentials);
setCurrentUser(response.user);
}, []);
const contextValue = useMemo(() => ({
currentUser,
login
}), [currentUser, login]);
return (
<AuthContext.Provider value={contextValue}>
<Page />
</AuthContext.Provider>
);
}
```
As a result of this change, even if `MyApp` needs to re-render, the components calling `useContext(AuthContext)` won’t need to re-render unless `currentUser` has changed.
Read more about [`useMemo`](https://react.dev/reference/react/useMemo) and [`useCallback`.](https://react.dev/reference/react/useCallback)
* * *
## Troubleshooting[Link for Troubleshooting]()
### My component doesn’t see the value from my provider[Link for My component doesn’t see the value from my provider]()
There are a few common ways that this can happen:
1. You’re rendering `<SomeContext.Provider>` in the same component (or below) as where you’re calling `useContext()`. Move `<SomeContext.Provider>` *above and outside* the component calling `useContext()`.
2. You may have forgotten to wrap your component with `<SomeContext.Provider>`, or you might have put it in a different part of the tree than you thought. Check whether the hierarchy is right using [React DevTools.](https://react.dev/learn/react-developer-tools)
3. You might be running into some build issue with your tooling that causes `SomeContext` as seen from the providing component and `SomeContext` as seen by the reading component to be two different objects. This can happen if you use symlinks, for example. You can verify this by assigning them to globals like `window.SomeContext1` and `window.SomeContext2` and then checking whether `window.SomeContext1 === window.SomeContext2` in the console. If they’re not the same, fix that issue on the build tool level.
### I am always getting `undefined` from my context although the default value is different[Link for this heading]()
You might have a provider without a `value` in the tree:
```
// 🚩 Doesn't work: no value prop
<ThemeContext.Provider>
<Button />
</ThemeContext.Provider>
```
If you forget to specify `value`, it’s like passing `value={undefined}`.
You may have also mistakingly used a different prop name by mistake:
```
// 🚩 Doesn't work: prop should be called "value"
<ThemeContext.Provider theme={theme}>
<Button />
</ThemeContext.Provider>
```
In both of these cases you should see a warning from React in the console. To fix them, call the prop `value`:
```
// ✅ Passing the value prop
<ThemeContext.Provider value={theme}>
<Button />
</ThemeContext.Provider>
```
Note that the [default value from your `createContext(defaultValue)` call]() is only used **if there is no matching provider above at all.** If there is a `<SomeContext.Provider value={undefined}>` component somewhere in the parent tree, the component calling `useContext(SomeContext)` *will* receive `undefined` as the context value.
[PrevioususeCallback](https://react.dev/reference/react/useCallback)
[NextuseDebugValue](https://react.dev/reference/react/useDebugValue) |
https://react.dev/reference/react/useId | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useId[Link for this heading]()
`useId` is a React Hook for generating unique IDs that can be passed to accessibility attributes.
```
const id = useId()
```
- [Reference]()
- [`useId()`]()
- [Usage]()
- [Generating unique IDs for accessibility attributes]()
- [Generating IDs for several related elements]()
- [Specifying a shared prefix for all generated IDs]()
- [Using the same ID prefix on the client and the server]()
* * *
## Reference[Link for Reference]()
### `useId()`[Link for this heading]()
Call `useId` at the top level of your component to generate a unique ID:
```
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
// ...
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
`useId` does not take any parameters.
#### Returns[Link for Returns]()
`useId` returns a unique ID string associated with this particular `useId` call in this particular component.
#### Caveats[Link for Caveats]()
- `useId` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
- `useId` **should not be used to generate keys** in a list. [Keys should be generated from your data.](https://react.dev/learn/rendering-lists)
* * *
## Usage[Link for Usage]()
### Pitfall
**Do not call `useId` to generate keys in a list.** [Keys should be generated from your data.](https://react.dev/learn/rendering-lists)
### Generating unique IDs for accessibility attributes[Link for Generating unique IDs for accessibility attributes]()
Call `useId` at the top level of your component to generate a unique ID:
```
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
// ...
```
You can then pass the generated ID to different attributes:
```
<>
<input type="password" aria-describedby={passwordHintId} />
<p id={passwordHintId}>
</>
```
**Let’s walk through an example to see when this is useful.**
[HTML accessibility attributes](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) like [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) let you specify that two tags are related to each other. For example, you can specify that an element (like an input) is described by another element (like a paragraph).
In regular HTML, you would write it like this:
```
<label>
Password:
<input
type="password"
aria-describedby="password-hint"
/>
</label>
<p id="password-hint">
The password should contain at least 18 characters
</p>
```
However, hardcoding IDs like this is not a good practice in React. A component may be rendered more than once on the page—but IDs have to be unique! Instead of hardcoding an ID, generate a unique ID with `useId`:
```
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
return (
<>
<label>
Password:
<input
type="password"
aria-describedby={passwordHintId}
/>
</label>
<p id={passwordHintId}>
The password should contain at least 18 characters
</p>
</>
);
}
```
Now, even if `PasswordField` appears multiple times on the screen, the generated IDs won’t clash.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
return (
<>
<label>
Password:
<input
type="password"
aria-describedby={passwordHintId}
/>
</label>
<p id={passwordHintId}>
The password should contain at least 18 characters
</p>
</>
);
}
export default function App() {
return (
<>
<h2>Choose password</h2>
<PasswordField />
<h2>Confirm password</h2>
<PasswordField />
</>
);
}
```
Show more
[Watch this video](https://www.youtube.com/watch?v=0dNzNcuEuOo) to see the difference in the user experience with assistive technologies.
### Pitfall
With [server rendering](https://react.dev/reference/react-dom/server), **`useId` requires an identical component tree on the server and the client**. If the trees you render on the server and the client don’t match exactly, the generated IDs won’t match.
##### Deep Dive
#### Why is useId better than an incrementing counter?[Link for Why is useId better than an incrementing counter?]()
Show Details
You might be wondering why `useId` is better than incrementing a global variable like `nextId++`.
The primary benefit of `useId` is that React ensures that it works with [server rendering.](https://react.dev/reference/react-dom/server) During server rendering, your components generate HTML output. Later, on the client, [hydration](https://react.dev/reference/react-dom/client/hydrateRoot) attaches your event handlers to the generated HTML. For hydration to work, the client output must match the server HTML.
This is very difficult to guarantee with an incrementing counter because the order in which the Client Components are hydrated may not match the order in which the server HTML was emitted. By calling `useId`, you ensure that hydration will work, and the output will match between the server and the client.
Inside React, `useId` is generated from the “parent path” of the calling component. This is why, if the client and the server tree are the same, the “parent path” will match up regardless of rendering order.
* * *
### Generating IDs for several related elements[Link for Generating IDs for several related elements]()
If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useId } from 'react';
export default function Form() {
const id = useId();
return (
<form>
<label htmlFor={id + '-firstName'}>First Name:</label>
<input id={id + '-firstName'} type="text" />
<hr />
<label htmlFor={id + '-lastName'}>Last Name:</label>
<input id={id + '-lastName'} type="text" />
</form>
);
}
```
This lets you avoid calling `useId` for every single element that needs a unique ID.
* * *
### Specifying a shared prefix for all generated IDs[Link for Specifying a shared prefix for all generated IDs]()
If you render multiple independent React applications on a single page, pass `identifierPrefix` as an option to your [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) or [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) calls. This ensures that the IDs generated by the two different apps never clash because every identifier generated with `useId` will start with the distinct prefix you’ve specified.
index.jsindex.htmlApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';
const root1 = createRoot(document.getElementById('root1'), {
identifierPrefix: 'my-first-app-'
});
root1.render(<App />);
const root2 = createRoot(document.getElementById('root2'), {
identifierPrefix: 'my-second-app-'
});
root2.render(<App />);
```
* * *
### Using the same ID prefix on the client and the server[Link for Using the same ID prefix on the client and the server]()
If you [render multiple independent React apps on the same page](), and some of these apps are server-rendered, make sure that the `identifierPrefix` you pass to the [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) call on the client side is the same as the `identifierPrefix` you pass to the [server APIs](https://react.dev/reference/react-dom/server) such as [`renderToPipeableStream`.](https://react.dev/reference/react-dom/server/renderToPipeableStream)
```
// Server
import { renderToPipeableStream } from 'react-dom/server';
const { pipe } = renderToPipeableStream(
<App />,
{ identifierPrefix: 'react-app1' }
);
```
```
// Client
import { hydrateRoot } from 'react-dom/client';
const domNode = document.getElementById('root');
const root = hydrateRoot(
domNode,
reactNode,
{ identifierPrefix: 'react-app1' }
);
```
You do not need to pass `identifierPrefix` if you only have one React app on the page.
[PrevioususeEffect](https://react.dev/reference/react/useEffect)
[NextuseImperativeHandle](https://react.dev/reference/react/useImperativeHandle) |
https://react.dev/reference/react/useImperativeHandle | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useImperativeHandle[Link for this heading]()
`useImperativeHandle` is a React Hook that lets you customize the handle exposed as a [ref.](https://react.dev/learn/manipulating-the-dom-with-refs)
```
useImperativeHandle(ref, createHandle, dependencies?)
```
- [Reference]()
- [`useImperativeHandle(ref, createHandle, dependencies?)`]()
- [Usage]()
- [Exposing a custom ref handle to the parent component]()
- [Exposing your own imperative methods]()
* * *
## Reference[Link for Reference]()
### `useImperativeHandle(ref, createHandle, dependencies?)`[Link for this heading]()
Call `useImperativeHandle` at the top level of your component to customize the ref handle it exposes:
```
import { useImperativeHandle } from 'react';
function MyInput({ ref }) {
useImperativeHandle(ref, () => {
return {
// ... your methods ...
};
}, []);
// ...
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `ref`: The `ref` you received as a prop to the `MyInput` component.
- `createHandle`: A function that takes no arguments and returns the ref handle you want to expose. That ref handle can have any type. Usually, you will return an object with the methods you want to expose.
- **optional** `dependencies`: The list of all reactive values referenced inside of the `createHandle` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](https://react.dev/learn/editor-setup), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. If a re-render resulted in a change to some dependency, or if you omitted this argument, your `createHandle` function will re-execute, and the newly created handle will be assigned to the ref.
### Note
Starting with React 19, [`ref` is available a prop.](https://react.dev/blog/2024/12/05/react-19) In React 18 and earlier, it was necessary to get the `ref` from [`forwardRef`.](https://react.dev/reference/react/forwardRef)
#### Returns[Link for Returns]()
`useImperativeHandle` returns `undefined`.
* * *
## Usage[Link for Usage]()
### Exposing a custom ref handle to the parent component[Link for Exposing a custom ref handle to the parent component]()
To expose a DOM node to the parent element, pass in the `ref` prop to the node.
```
function MyInput({ ref }) {
return <input ref={ref} />;
};
```
With the code above, [a ref to `MyInput` will receive the `<input>` DOM node.](https://react.dev/learn/manipulating-the-dom-with-refs) However, you can expose a custom value instead. To customize the exposed handle, call `useImperativeHandle` at the top level of your component:
```
import { useImperativeHandle } from 'react';
function MyInput({ ref }) {
useImperativeHandle(ref, () => {
return {
// ... your methods ...
};
}, []);
return <input />;
};
```
Note that in the code above, the `ref` is no longer passed to the `<input>`.
For example, suppose you don’t want to expose the entire `<input>` DOM node, but you want to expose two of its methods: `focus` and `scrollIntoView`. To do this, keep the real browser DOM in a separate ref. Then use `useImperativeHandle` to expose a handle with only the methods that you want the parent component to call:
```
import { useRef, useImperativeHandle } from 'react';
function MyInput({ ref }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => {
return {
focus() {
inputRef.current.focus();
},
scrollIntoView() {
inputRef.current.scrollIntoView();
},
};
}, []);
return <input ref={inputRef} />;
};
```
Now, if the parent component gets a ref to `MyInput`, it will be able to call the `focus` and `scrollIntoView` methods on it. However, it will not have full access to the underlying `<input>` DOM node.
App.jsMyInput.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef } from 'react';
import MyInput from './MyInput.js';
export default function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
// This won't work because the DOM node isn't exposed:
// ref.current.style.opacity = 0.5;
}
return (
<form>
<MyInput placeholder="Enter your name" ref={ref} />
<button type="button" onClick={handleClick}>
Edit
</button>
</form>
);
}
```
Show more
* * *
### Exposing your own imperative methods[Link for Exposing your own imperative methods]()
The methods you expose via an imperative handle don’t have to match the DOM methods exactly. For example, this `Post` component exposes a `scrollAndFocusAddComment` method via an imperative handle. This lets the parent `Page` scroll the list of comments *and* focus the input field when you click the button:
App.jsPost.jsCommentList.jsAddComment.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef } from 'react';
import Post from './Post.js';
export default function Page() {
const postRef = useRef(null);
function handleClick() {
postRef.current.scrollAndFocusAddComment();
}
return (
<>
<button onClick={handleClick}>
Write a comment
</button>
<Post ref={postRef} />
</>
);
}
```
Show more
### Pitfall
**Do not overuse refs.** You should only use refs for *imperative* behaviors that you can’t express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](https://react.dev/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
[PrevioususeId](https://react.dev/reference/react/useId)
[NextuseInsertionEffect](https://react.dev/reference/react/useInsertionEffect) |
https://react.dev/reference/react/useActionState | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useActionState[Link for this heading]()
`useActionState` is a Hook that allows you to update state based on the result of a form action.
```
const [state, formAction, isPending] = useActionState(fn, initialState, permalink?);
```
### Note
In earlier React Canary versions, this API was part of React DOM and called `useFormState`.
- [Reference]()
- [`useActionState(action, initialState, permalink?)`]()
- [Usage]()
- [Using information returned by a form action]()
- [Troubleshooting]()
- [My action can no longer read the submitted form data]()
* * *
## Reference[Link for Reference]()
### `useActionState(action, initialState, permalink?)`[Link for this heading]()
Call `useActionState` at the top level of your component to create component state that is updated [when a form action is invoked](https://react.dev/reference/react-dom/components/form). You pass `useActionState` an existing form action function as well as an initial state, and it returns a new action that you use in your form, along with the latest form state and whether the Action is still pending. The latest form state is also passed to the function that you provided.
```
import { useActionState } from "react";
async function increment(previousState, formData) {
return previousState + 1;
}
function StatefulForm({}) {
const [state, formAction] = useActionState(increment, 0);
return (
<form>
{state}
<button formAction={formAction}>Increment</button>
</form>
)
}
```
The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass.
If used with a Server Function, `useActionState` allows the server’s response from submitting the form to be shown even before hydration has completed.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `fn`: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the `initialState` that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
- `initialState`: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
- **optional** `permalink`: A string containing the unique page URL that this form modifies. For use on pages with dynamic content (eg: feeds) in conjunction with progressive enhancement: if `fn` is a [server function](https://react.dev/reference/rsc/server-functions) and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page’s URL. Ensure that the same form component is rendered on the destination page (including the same action `fn` and `permalink`) so that React knows how to pass the state through. Once the form has been hydrated, this parameter has no effect.
#### Returns[Link for Returns]()
`useActionState` returns an array with the following values:
1. The current state. During the first render, it will match the `initialState` you have passed. After the action is invoked, it will match the value returned by the action.
2. A new action that you can pass as the `action` prop to your `form` component or `formAction` prop to any `button` component within the form.
3. The `isPending` flag that tells you whether there is a pending Transition.
#### Caveats[Link for Caveats]()
- When used with a framework that supports React Server Components, `useActionState` lets you make forms interactive before JavaScript has executed on the client. When used without Server Components, it is equivalent to component local state.
- The function passed to `useActionState` receives an extra argument, the previous or initial state, as its first argument. This makes its signature different than if it were used directly as a form action without using `useActionState`.
* * *
## Usage[Link for Usage]()
### Using information returned by a form action[Link for Using information returned by a form action]()
Call `useActionState` at the top level of your component to access the return value of an action from the last time a form was submitted.
```
import { useActionState } from 'react';
import { action } from './actions.js';
function MyComponent() {
const [state, formAction] = useActionState(action, null);
// ...
return (
<form action={formAction}>
{/* ... */}
</form>
);
}
```
`useActionState` returns an array with the following items:
1. The current state of the form, which is initially set to the initial state you provided, and after the form is submitted is set to the return value of the action you provided.
2. A new action that you pass to `<form>` as its `action` prop.
3. A pending state that you can utilise whilst your action is processing.
When the form is submitted, the action function that you provided will be called. Its return value will become the new current state of the form.
The action that you provide will also receive a new first argument, namely the current state of the form. The first time the form is submitted, this will be the initial state you provided, while with subsequent submissions, it will be the return value from the last time the action was called. The rest of the arguments are the same as if `useActionState` had not been used.
```
function action(currentState, formData) {
// ...
return 'next state';
}
```
#### Display information after submitting a form[Link for Display information after submitting a form]()
1\. Display form errors 2. Display structured information after submitting a form
#### Example 1 of 2: Display form errors[Link for this heading]()
To display messages such as an error message or toast that’s returned by a Server Function, wrap the action in a call to `useActionState`.
App.jsactions.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useActionState, useState } from "react";
import { addToCart } from "./actions.js";
function AddToCartForm({itemID, itemTitle}) {
const [message, formAction, isPending] = useActionState(addToCart, null);
return (
<form action={formAction}>
<h2>{itemTitle}</h2>
<input type="hidden" name="itemID" value={itemID} />
<button type="submit">Add to Cart</button>
{isPending ? "Loading..." : message}
</form>
);
}
export default function App() {
return (
<>
<AddToCartForm itemID="1" itemTitle="JavaScript: The Definitive Guide" />
<AddToCartForm itemID="2" itemTitle="JavaScript: The Good Parts" />
</>
)
}
```
Show more
Next Example
## Troubleshooting[Link for Troubleshooting]()
### My action can no longer read the submitted form data[Link for My action can no longer read the submitted form data]()
When you wrap an action with `useActionState`, it gets an extra argument *as its first argument*. The submitted form data is therefore its *second* argument instead of its first as it would usually be. The new first argument that gets added is the current state of the form.
```
function action(currentState, formData) {
// ...
}
```
[PreviousHooks](https://react.dev/reference/react/hooks)
[NextuseCallback](https://react.dev/reference/react/useCallback) |
https://react.dev/reference/react/useMemo | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useMemo[Link for this heading]()
`useMemo` is a React Hook that lets you cache the result of a calculation between re-renders.
```
const cachedValue = useMemo(calculateValue, dependencies)
```
- [Reference]()
- [`useMemo(calculateValue, dependencies)`]()
- [Usage]()
- [Skipping expensive recalculations]()
- [Skipping re-rendering of components]()
- [Preventing an Effect from firing too often]()
- [Memoizing a dependency of another Hook]()
- [Memoizing a function]()
- [Troubleshooting]()
- [My calculation runs twice on every re-render]()
- [My `useMemo` call is supposed to return an object, but returns undefined]()
- [Every time my component renders, the calculation in `useMemo` re-runs]()
- [I need to call `useMemo` for each list item in a loop, but it’s not allowed]()
* * *
## Reference[Link for Reference]()
### `useMemo(calculateValue, dependencies)`[Link for this heading]()
Call `useMemo` at the top level of your component to cache a calculation between re-renders:
```
import { useMemo } from 'react';
function TodoList({ todos, tab }) {
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab]
);
// ...
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `calculateValue`: The function calculating the value that you want to cache. It should be pure, should take no arguments, and should return a value of any type. React will call your function during the initial render. On next renders, React will return the same value again if the `dependencies` have not changed since the last render. Otherwise, it will call `calculateValue`, return its result, and store it so it can be reused later.
- `dependencies`: The list of all reactive values referenced inside of the `calculateValue` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](https://react.dev/learn/editor-setup), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison.
#### Returns[Link for Returns]()
On the initial render, `useMemo` returns the result of calling `calculateValue` with no arguments.
During next renders, it will either return an already stored value from the last render (if the dependencies haven’t changed), or call `calculateValue` again, and return the result that `calculateValue` has returned.
#### Caveats[Link for Caveats]()
- `useMemo` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
- In Strict Mode, React will **call your calculation function twice** in order to [help you find accidental impurities.]() This is development-only behavior and does not affect production. If your calculation function is pure (as it should be), this should not affect your logic. The result from one of the calls will be ignored.
- React **will not throw away the cached value unless there is a specific reason to do that.** For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should be fine if you rely on `useMemo` solely as a performance optimization. Otherwise, a [state variable](https://react.dev/reference/react/useState) or a [ref](https://react.dev/reference/react/useRef) may be more appropriate.
### Note
Caching return values like this is also known as [*memoization*,](https://en.wikipedia.org/wiki/Memoization) which is why this Hook is called `useMemo`.
* * *
## Usage[Link for Usage]()
### Skipping expensive recalculations[Link for Skipping expensive recalculations]()
To cache a calculation between re-renders, wrap it in a `useMemo` call at the top level of your component:
```
import { useMemo } from 'react';
function TodoList({ todos, tab, theme }) {
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
// ...
}
```
You need to pass two things to `useMemo`:
1. A calculation function that takes no arguments, like `() =>`, and returns what you wanted to calculate.
2. A list of dependencies including every value within your component that’s used inside your calculation.
On the initial render, the value you’ll get from `useMemo` will be the result of calling your calculation.
On every subsequent render, React will compare the dependencies with the dependencies you passed during the last render. If none of the dependencies have changed (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), `useMemo` will return the value you already calculated before. Otherwise, React will re-run your calculation and return the new value.
In other words, `useMemo` caches a calculation result between re-renders until its dependencies change.
**Let’s walk through an example to see when this is useful.**
By default, React will re-run the entire body of your component every time that it re-renders. For example, if this `TodoList` updates its state or receives new props from its parent, the `filterTodos` function will re-run:
```
function TodoList({ todos, tab, theme }) {
const visibleTodos = filterTodos(todos, tab);
// ...
}
```
Usually, this isn’t a problem because most calculations are very fast. However, if you’re filtering or transforming a large array, or doing some expensive computation, you might want to skip doing it again if data hasn’t changed. If both `todos` and `tab` are the same as they were during the last render, wrapping the calculation in `useMemo` like earlier lets you reuse `visibleTodos` you’ve already calculated before.
This type of caching is called [*memoization.*](https://en.wikipedia.org/wiki/Memoization)
### Note
**You should only rely on `useMemo` as a performance optimization.** If your code doesn’t work without it, find the underlying problem and fix it first. Then you may add `useMemo` to improve performance.
##### Deep Dive
#### How to tell if a calculation is expensive?[Link for How to tell if a calculation is expensive?]()
Show Details
In general, unless you’re creating or looping over thousands of objects, it’s probably not expensive. If you want to get more confidence, you can add a console log to measure the time spent in a piece of code:
```
console.time('filter array');
const visibleTodos = filterTodos(todos, tab);
console.timeEnd('filter array');
```
Perform the interaction you’re measuring (for example, typing into the input). You will then see logs like `filter array: 0.15ms` in your console. If the overall logged time adds up to a significant amount (say, `1ms` or more), it might make sense to memoize that calculation. As an experiment, you can then wrap the calculation in `useMemo` to verify whether the total logged time has decreased for that interaction or not:
```
console.time('filter array');
const visibleTodos = useMemo(() => {
return filterTodos(todos, tab); // Skipped if todos and tab haven't changed
}, [todos, tab]);
console.timeEnd('filter array');
```
`useMemo` won’t make the *first* render faster. It only helps you skip unnecessary work on updates.
Keep in mind that your machine is probably faster than your users’ so it’s a good idea to test the performance with an artificial slowdown. For example, Chrome offers a [CPU Throttling](https://developer.chrome.com/blog/new-in-devtools-61/) option for this.
Also note that measuring performance in development will not give you the most accurate results. (For example, when [Strict Mode](https://react.dev/reference/react/StrictMode) is on, you will see each component render twice rather than once.) To get the most accurate timings, build your app for production and test it on a device like your users have.
##### Deep Dive
#### Should you add useMemo everywhere?[Link for Should you add useMemo everywhere?]()
Show Details
If your app is like this site, and most interactions are coarse (like replacing a page or an entire section), memoization is usually unnecessary. On the other hand, if your app is more like a drawing editor, and most interactions are granular (like moving shapes), then you might find memoization very helpful.
Optimizing with `useMemo` is only valuable in a few cases:
- The calculation you’re putting in `useMemo` is noticeably slow, and its dependencies rarely change.
- You pass it as a prop to a component wrapped in [`memo`.](https://react.dev/reference/react/memo) You want to skip re-rendering if the value hasn’t changed. Memoization lets your component re-render only when dependencies aren’t the same.
- The value you’re passing is later used as a dependency of some Hook. For example, maybe another `useMemo` calculation value depends on it. Or maybe you are depending on this value from [`useEffect.`](https://react.dev/reference/react/useEffect)
There is no benefit to wrapping a calculation in `useMemo` in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside of this approach is that code becomes less readable. Also, not all memoization is effective: a single value that’s “always new” is enough to break memoization for an entire component.
**In practice, you can make a lot of memoization unnecessary by following a few principles:**
1. When a component visually wraps other components, let it [accept JSX as children.](https://react.dev/learn/passing-props-to-a-component) This way, when the wrapper component updates its own state, React knows that its children don’t need to re-render.
2. Prefer local state and don’t [lift state up](https://react.dev/learn/sharing-state-between-components) any further than necessary. For example, don’t keep transient state like forms and whether an item is hovered at the top of your tree or in a global state library.
3. Keep your [rendering logic pure.](https://react.dev/learn/keeping-components-pure) If re-rendering a component causes a problem or produces some noticeable visual artifact, it’s a bug in your component! Fix the bug instead of adding memoization.
4. Avoid [unnecessary Effects that update state.](https://react.dev/learn/you-might-not-need-an-effect) Most performance problems in React apps are caused by chains of updates originating from Effects that cause your components to render over and over.
5. Try to [remove unnecessary dependencies from your Effects.](https://react.dev/learn/removing-effect-dependencies) For example, instead of memoization, it’s often simpler to move some object or a function inside an Effect or outside the component.
If a specific interaction still feels laggy, [use the React Developer Tools profiler](https://legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html) to see which components would benefit the most from memoization, and add memoization where needed. These principles make your components easier to debug and understand, so it’s good to follow them in any case. In the long term, we’re researching [doing granular memoization automatically](https://www.youtube.com/watch?v=lGEMwh32soc) to solve this once and for all.
#### The difference between useMemo and calculating a value directly[Link for The difference between useMemo and calculating a value directly]()
1\. Skipping recalculation with `useMemo` 2. Always recalculating a value
#### Example 1 of 2: Skipping recalculation with `useMemo`[Link for this heading]()
In this example, the `filterTodos` implementation is **artificially slowed down** so that you can see what happens when some JavaScript function you’re calling during rendering is genuinely slow. Try switching the tabs and toggling the theme.
Switching the tabs feels slow because it forces the slowed down `filterTodos` to re-execute. That’s expected because the `tab` has changed, and so the entire calculation *needs* to re-run. (If you’re curious why it runs twice, it’s explained [here.]())
Toggle the theme. **Thanks to `useMemo`, it’s fast despite the artificial slowdown!** The slow `filterTodos` call was skipped because both `todos` and `tab` (which you pass as dependencies to `useMemo`) haven’t changed since the last render.
App.jsTodoList.jsutils.js
TodoList.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useMemo } from 'react';
import { filterTodos } from './utils.js'
export default function TodoList({ todos, theme, tab }) {
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab]
);
return (
<div className={theme}>
<p><b>Note: <code>filterTodos</code> is artificially slowed down!</b></p>
<ul>
{visibleTodos.map(todo => (
<li key={todo.id}>
{todo.completed ?
<s>{todo.text}</s> :
todo.text
}
</li>
))}
</ul>
</div>
);
}
```
Show more
Next Example
* * *
### Skipping re-rendering of components[Link for Skipping re-rendering of components]()
In some cases, `useMemo` can also help you optimize performance of re-rendering child components. To illustrate this, let’s say this `TodoList` component passes the `visibleTodos` as a prop to the child `List` component:
```
export default function TodoList({ todos, tab, theme }) {
// ...
return (
<div className={theme}>
<List items={visibleTodos} />
</div>
);
}
```
You’ve noticed that toggling the `theme` prop freezes the app for a moment, but if you remove `<List />` from your JSX, it feels fast. This tells you that it’s worth trying to optimize the `List` component.
**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `TodoList` re-renders with a different `theme`, the `List` component *also* re-renders. This is fine for components that don’t require much calculation to re-render. But if you’ve verified that a re-render is slow, you can tell `List` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](https://react.dev/reference/react/memo)
```
import { memo } from 'react';
const List = memo(function List({ items }) {
// ...
});
```
**With this change, `List` will skip re-rendering if all of its props are the *same* as on the last render.** This is where caching the calculation becomes important! Imagine that you calculated `visibleTodos` without `useMemo`:
```
export default function TodoList({ todos, tab, theme }) {
// Every time the theme changes, this will be a different array...
const visibleTodos = filterTodos(todos, tab);
return (
<div className={theme}>
{/* ... so List's props will never be the same, and it will re-render every time */}
<List items={visibleTodos} />
</div>
);
}
```
**In the above example, the `filterTodos` function always creates a *different* array,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn’t be a problem, but it means that `List` props will never be the same, and your [`memo`](https://react.dev/reference/react/memo) optimization won’t work. This is where `useMemo` comes in handy:
```
export default function TodoList({ todos, tab, theme }) {
// Tell React to cache your calculation between re-renders...
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab] // ...so as long as these dependencies don't change...
);
return (
<div className={theme}>
{/* ...List will receive the same props and can skip re-rendering */}
<List items={visibleTodos} />
</div>
);
}
```
**By wrapping the `visibleTodos` calculation in `useMemo`, you ensure that it has the *same* value between the re-renders** (until dependencies change). You don’t *have to* wrap a calculation in `useMemo` unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in [`memo`,](https://react.dev/reference/react/memo) and this lets it skip re-rendering. There are a few other reasons to add `useMemo` which are described further on this page.
##### Deep Dive
#### Memoizing individual JSX nodes[Link for Memoizing individual JSX nodes]()
Show Details
Instead of wrapping `List` in [`memo`](https://react.dev/reference/react/memo), you could wrap the `<List />` JSX node itself in `useMemo`:
```
export default function TodoList({ todos, tab, theme }) {
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
const children = useMemo(() => <List items={visibleTodos} />, [visibleTodos]);
return (
<div className={theme}>
{children}
</div>
);
}
```
The behavior would be the same. If the `visibleTodos` haven’t changed, `List` won’t be re-rendered.
A JSX node like `<List items={visibleTodos} />` is an object like `{ type: List, props: { items: visibleTodos } }`. Creating this object is very cheap, but React doesn’t know whether its contents is the same as last time or not. This is why by default, React will re-render the `List` component.
However, if React sees the same exact JSX as during the previous render, it won’t try to re-render your component. This is because JSX nodes are [immutable.](https://en.wikipedia.org/wiki/Immutable_object) A JSX node object could not have changed over time, so React knows it’s safe to skip a re-render. However, for this to work, the node has to *actually be the same object*, not merely look the same in code. This is what `useMemo` does in this example.
Manually wrapping JSX nodes into `useMemo` is not convenient. For example, you can’t do this conditionally. This is usually why you would wrap components with [`memo`](https://react.dev/reference/react/memo) instead of wrapping JSX nodes.
#### The difference between skipping re-renders and always re-rendering[Link for The difference between skipping re-renders and always re-rendering]()
1\. Skipping re-rendering with `useMemo` and `memo` 2. Always re-rendering a component
#### Example 1 of 2: Skipping re-rendering with `useMemo` and `memo`[Link for this heading]()
In this example, the `List` component is **artificially slowed down** so that you can see what happens when a React component you’re rendering is genuinely slow. Try switching the tabs and toggling the theme.
Switching the tabs feels slow because it forces the slowed down `List` to re-render. That’s expected because the `tab` has changed, and so you need to reflect the user’s new choice on the screen.
Next, try toggling the theme. **Thanks to `useMemo` together with [`memo`](https://react.dev/reference/react/memo), it’s fast despite the artificial slowdown!** The `List` skipped re-rendering because the `visibleTodos` array has not changed since the last render. The `visibleTodos` array has not changed because both `todos` and `tab` (which you pass as dependencies to `useMemo`) haven’t changed since the last render.
App.jsTodoList.jsList.jsutils.js
TodoList.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useMemo } from 'react';
import List from './List.js';
import { filterTodos } from './utils.js'
export default function TodoList({ todos, theme, tab }) {
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab]
);
return (
<div className={theme}>
<p><b>Note: <code>List</code> is artificially slowed down!</b></p>
<List items={visibleTodos} />
</div>
);
}
```
Show more
Next Example
* * *
### Preventing an Effect from firing too often[Link for Preventing an Effect from firing too often]()
Sometimes, you might want to use a value inside an [Effect:](https://react.dev/learn/synchronizing-with-effects)
```
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const options = {
serverUrl: 'https://localhost:1234',
roomId: roomId
}
useEffect(() => {
const connection = createConnection(options);
connection.connect();
// ...
```
This creates a problem. [Every reactive value must be declared as a dependency of your Effect.](https://react.dev/learn/lifecycle-of-reactive-effects) However, if you declare `options` as a dependency, it will cause your Effect to constantly reconnect to the chat room:
```
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // 🔴 Problem: This dependency changes on every render
// ...
```
To solve this, you can wrap the object you need to call from an Effect in `useMemo`:
```
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const options = useMemo(() => {
return {
serverUrl: 'https://localhost:1234',
roomId: roomId
};
}, [roomId]); // ✅ Only changes when roomId changes
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // ✅ Only changes when options changes
// ...
```
This ensures that the `options` object is the same between re-renders if `useMemo` returns the cached object.
However, since `useMemo` is performance optimization, not a semantic guarantee, React may throw away the cached value if [there is a specific reason to do that](). This will also cause the effect to re-fire, **so it’s even better to remove the need for a function dependency** by moving your object *inside* the Effect:
```
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
const options = { // ✅ No need for useMemo or object dependencies!
serverUrl: 'https://localhost:1234',
roomId: roomId
}
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ Only changes when roomId changes
// ...
```
Now your code is simpler and doesn’t need `useMemo`. [Learn more about removing Effect dependencies.](https://react.dev/learn/removing-effect-dependencies)
### Memoizing a dependency of another Hook[Link for Memoizing a dependency of another Hook]()
Suppose you have a calculation that depends on an object created directly in the component body:
```
function Dropdown({ allItems, text }) {
const searchOptions = { matchMode: 'whole-word', text };
const visibleItems = useMemo(() => {
return searchItems(allItems, searchOptions);
}, [allItems, searchOptions]); // 🚩 Caution: Dependency on an object created in the component body
// ...
```
Depending on an object like this defeats the point of memoization. When a component re-renders, all of the code directly inside the component body runs again. **The lines of code creating the `searchOptions` object will also run on every re-render.** Since `searchOptions` is a dependency of your `useMemo` call, and it’s different every time, React knows the dependencies are different, and recalculate `searchItems` every time.
To fix this, you could memoize the `searchOptions` object *itself* before passing it as a dependency:
```
function Dropdown({ allItems, text }) {
const searchOptions = useMemo(() => {
return { matchMode: 'whole-word', text };
}, [text]); // ✅ Only changes when text changes
const visibleItems = useMemo(() => {
return searchItems(allItems, searchOptions);
}, [allItems, searchOptions]); // ✅ Only changes when allItems or searchOptions changes
// ...
```
In the example above, if the `text` did not change, the `searchOptions` object also won’t change. However, an even better fix is to move the `searchOptions` object declaration *inside* of the `useMemo` calculation function:
```
function Dropdown({ allItems, text }) {
const visibleItems = useMemo(() => {
const searchOptions = { matchMode: 'whole-word', text };
return searchItems(allItems, searchOptions);
}, [allItems, text]); // ✅ Only changes when allItems or text changes
// ...
```
Now your calculation depends on `text` directly (which is a string and can’t “accidentally” become different).
* * *
### Memoizing a function[Link for Memoizing a function]()
Suppose the `Form` component is wrapped in [`memo`.](https://react.dev/reference/react/memo) You want to pass a function to it as a prop:
```
export default function ProductPage({ productId, referrer }) {
function handleSubmit(orderDetails) {
post('/product/' + productId + '/buy', {
referrer,
orderDetails
});
}
return <Form onSubmit={handleSubmit} />;
}
```
Just as `{}` creates a different object, function declarations like `function() {}` and expressions like `() => {}` produce a *different* function on every re-render. By itself, creating a new function is not a problem. This is not something to avoid! However, if the `Form` component is memoized, presumably you want to skip re-rendering it when no props have changed. A prop that is *always* different would defeat the point of memoization.
To memoize a function with `useMemo`, your calculation function would have to return another function:
```
export default function Page({ productId, referrer }) {
const handleSubmit = useMemo(() => {
return (orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails
});
};
}, [productId, referrer]);
return <Form onSubmit={handleSubmit} />;
}
```
This looks clunky! **Memoizing functions is common enough that React has a built-in Hook specifically for that. Wrap your functions into [`useCallback`](https://react.dev/reference/react/useCallback) instead of `useMemo`** to avoid having to write an extra nested function:
```
export default function Page({ productId, referrer }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails
});
}, [productId, referrer]);
return <Form onSubmit={handleSubmit} />;
}
```
The two examples above are completely equivalent. The only benefit to `useCallback` is that it lets you avoid writing an extra nested function inside. It doesn’t do anything else. [Read more about `useCallback`.](https://react.dev/reference/react/useCallback)
* * *
## Troubleshooting[Link for Troubleshooting]()
### My calculation runs twice on every re-render[Link for My calculation runs twice on every re-render]()
In [Strict Mode](https://react.dev/reference/react/StrictMode), React will call some of your functions twice instead of once:
```
function TodoList({ todos, tab }) {
// This component function will run twice for every render.
const visibleTodos = useMemo(() => {
// This calculation will run twice if any of the dependencies change.
return filterTodos(todos, tab);
}, [todos, tab]);
// ...
```
This is expected and shouldn’t break your code.
This **development-only** behavior helps you [keep components pure.](https://react.dev/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component and calculation functions are pure, this shouldn’t affect your logic. However, if they are accidentally impure, this helps you notice and fix the mistake.
For example, this impure calculation function mutates an array you received as a prop:
```
const visibleTodos = useMemo(() => {
// 🚩 Mistake: mutating a prop
todos.push({ id: 'last', text: 'Go for a walk!' });
const filtered = filterTodos(todos, tab);
return filtered;
}, [todos, tab]);
```
React calls your function twice, so you’d notice the todo is added twice. Your calculation shouldn’t change any existing objects, but it’s okay to change any *new* objects you created during the calculation. For example, if the `filterTodos` function always returns a *different* array, you can mutate *that* array instead:
```
const visibleTodos = useMemo(() => {
const filtered = filterTodos(todos, tab);
// ✅ Correct: mutating an object you created during the calculation
filtered.push({ id: 'last', text: 'Go for a walk!' });
return filtered;
}, [todos, tab]);
```
Read [keeping components pure](https://react.dev/learn/keeping-components-pure) to learn more about purity.
Also, check out the guides on [updating objects](https://react.dev/learn/updating-objects-in-state) and [updating arrays](https://react.dev/learn/updating-arrays-in-state) without mutation.
* * *
### My `useMemo` call is supposed to return an object, but returns undefined[Link for this heading]()
This code doesn’t work:
```
// 🔴 You can't return an object from an arrow function with () => {
const searchOptions = useMemo(() => {
matchMode: 'whole-word',
text: text
}, [text]);
```
In JavaScript, `() => {` starts the arrow function body, so the `{` brace is not a part of your object. This is why it doesn’t return an object, and leads to mistakes. You could fix it by adding parentheses like `({` and `})`:
```
// This works, but is easy for someone to break again
const searchOptions = useMemo(() => ({
matchMode: 'whole-word',
text: text
}), [text]);
```
However, this is still confusing and too easy for someone to break by removing the parentheses.
To avoid this mistake, write a `return` statement explicitly:
```
// ✅ This works and is explicit
const searchOptions = useMemo(() => {
return {
matchMode: 'whole-word',
text: text
};
}, [text]);
```
* * *
### Every time my component renders, the calculation in `useMemo` re-runs[Link for this heading]()
Make sure you’ve specified the dependency array as a second argument!
If you forget the dependency array, `useMemo` will re-run the calculation every time:
```
function TodoList({ todos, tab }) {
// 🔴 Recalculates every time: no dependency array
const visibleTodos = useMemo(() => filterTodos(todos, tab));
// ...
```
This is the corrected version passing the dependency array as a second argument:
```
function TodoList({ todos, tab }) {
// ✅ Does not recalculate unnecessarily
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
// ...
```
If this doesn’t help, then the problem is that at least one of your dependencies is different from the previous render. You can debug this problem by manually logging your dependencies to the console:
```
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
console.log([todos, tab]);
```
You can then right-click on the arrays from different re-renders in the console and select “Store as a global variable” for both of them. Assuming the first one got saved as `temp1` and the second one got saved as `temp2`, you can then use the browser console to check whether each dependency in both arrays is the same:
```
Object.is(temp1[0], temp2[0]); // Is the first dependency the same between the arrays?
Object.is(temp1[1], temp2[1]); // Is the second dependency the same between the arrays?
Object.is(temp1[2], temp2[2]); // ... and so on for every dependency ...
```
When you find which dependency breaks memoization, either find a way to remove it, or [memoize it as well.]()
* * *
### I need to call `useMemo` for each list item in a loop, but it’s not allowed[Link for this heading]()
Suppose the `Chart` component is wrapped in [`memo`](https://react.dev/reference/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can’t call `useMemo` in a loop:
```
function ReportList({ items }) {
return (
<article>
{items.map(item => {
// 🔴 You can't call useMemo in a loop like this:
const data = useMemo(() => calculateReport(item), [item]);
return (
<figure key={item.id}>
<Chart data={data} />
</figure>
);
})}
</article>
);
}
```
Instead, extract a component for each item and memoize data for individual items:
```
function ReportList({ items }) {
return (
<article>
{items.map(item =>
<Report key={item.id} item={item} />
)}
</article>
);
}
function Report({ item }) {
// ✅ Call useMemo at the top level:
const data = useMemo(() => calculateReport(item), [item]);
return (
<figure>
<Chart data={data} />
</figure>
);
}
```
Alternatively, you could remove `useMemo` and instead wrap `Report` itself in [`memo`.](https://react.dev/reference/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
```
function ReportList({ items }) {
// ...
}
const Report = memo(function Report({ item }) {
const data = calculateReport(item);
return (
<figure>
<Chart data={data} />
</figure>
);
});
```
[PrevioususeLayoutEffect](https://react.dev/reference/react/useLayoutEffect)
[NextuseOptimistic](https://react.dev/reference/react/useOptimistic) |
https://react.dev/reference/react/useLayoutEffect | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useLayoutEffect[Link for this heading]()
### Pitfall
`useLayoutEffect` can hurt performance. Prefer [`useEffect`](https://react.dev/reference/react/useEffect) when possible.
`useLayoutEffect` is a version of [`useEffect`](https://react.dev/reference/react/useEffect) that fires before the browser repaints the screen.
```
useLayoutEffect(setup, dependencies?)
```
- [Reference]()
- [`useLayoutEffect(setup, dependencies?)`]()
- [Usage]()
- [Measuring layout before the browser repaints the screen]()
- [Troubleshooting]()
- [I’m getting an error: “`useLayoutEffect` does nothing on the server”]()
* * *
## Reference[Link for Reference]()
### `useLayoutEffect(setup, dependencies?)`[Link for this heading]()
Call `useLayoutEffect` to perform the layout measurements before the browser repaints the screen:
```
import { useState, useRef, useLayoutEffect } from 'react';
function Tooltip() {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height);
}, []);
// ...
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `setup`: The function with your Effect’s logic. Your setup function may also optionally return a *cleanup* function. Before your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. Before your component is removed from the DOM, React will run your cleanup function.
- **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](https://react.dev/learn/editor-setup), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. If you omit this argument, your Effect will re-run after every re-render of the component.
#### Returns[Link for Returns]()
`useLayoutEffect` returns `undefined`.
#### Caveats[Link for Caveats]()
- `useLayoutEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a component and move the Effect there.
- When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic “mirrors” your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [implement the cleanup function.](https://react.dev/learn/synchronizing-with-effects)
- If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object](https://react.dev/reference/react/useEffect) and [function](https://react.dev/reference/react/useEffect) dependencies. You can also [extract state updates](https://react.dev/reference/react/useEffect) and [non-reactive logic](https://react.dev/reference/react/useEffect) outside of your Effect.
- Effects **only run on the client.** They don’t run during server rendering.
- The code inside `useLayoutEffect` and all state updates scheduled from it **block the browser from repainting the screen.** When used excessively, this makes your app slow. When possible, prefer [`useEffect`.](https://react.dev/reference/react/useEffect)
- If you trigger a state update inside `useLayoutEffect`, React will execute all remaining Effects immediately including `useEffect`.
* * *
## Usage[Link for Usage]()
### Measuring layout before the browser repaints the screen[Link for Measuring layout before the browser repaints the screen]()
Most components don’t need to know their position and size on the screen to decide what to render. They only return some JSX. Then the browser calculates their *layout* (position and size) and repaints the screen.
Sometimes, that’s not enough. Imagine a tooltip that appears next to some element on hover. If there’s enough space, the tooltip should appear above the element, but if it doesn’t fit, it should appear below. In order to render the tooltip at the right final position, you need to know its height (i.e. whether it fits at the top).
To do this, you need to render in two passes:
1. Render the tooltip anywhere (even with a wrong position).
2. Measure its height and decide where to place the tooltip.
3. Render the tooltip *again* in the correct place.
**All of this needs to happen before the browser repaints the screen.** You don’t want the user to see the tooltip moving. Call `useLayoutEffect` to perform the layout measurements before the browser repaints the screen:
```
function Tooltip() {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0); // You don't know real height yet
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height); // Re-render now that you know the real height
}, []);
// ...use tooltipHeight in the rendering logic below...
}
```
Here’s how this works step by step:
1. `Tooltip` renders with the initial `tooltipHeight = 0` (so the tooltip may be wrongly positioned).
2. React places it in the DOM and runs the code in `useLayoutEffect`.
3. Your `useLayoutEffect` [measures the height](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of the tooltip content and triggers an immediate re-render.
4. `Tooltip` renders again with the real `tooltipHeight` (so the tooltip is correctly positioned).
5. React updates it in the DOM, and the browser finally displays the tooltip.
Hover over the buttons below and see how the tooltip adjusts its position depending on whether it fits:
App.jsButtonWithTooltip.jsTooltip.jsTooltipContainer.js
Tooltip.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef, useLayoutEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import TooltipContainer from './TooltipContainer.js';
export default function Tooltip({ children, targetRect }) {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height);
console.log('Measured tooltip height: ' + height);
}, []);
let tooltipX = 0;
let tooltipY = 0;
if (targetRect !== null) {
tooltipX = targetRect.left;
tooltipY = targetRect.top - tooltipHeight;
if (tooltipY < 0) {
// It doesn't fit above, so place below.
tooltipY = targetRect.bottom;
}
}
return createPortal(
<TooltipContainer x={tooltipX} y={tooltipY} contentRef={ref}>
{children}
</TooltipContainer>,
document.body
);
}
```
Show more
Notice that even though the `Tooltip` component has to render in two passes (first, with `tooltipHeight` initialized to `0` and then with the real measured height), you only see the final result. This is why you need `useLayoutEffect` instead of [`useEffect`](https://react.dev/reference/react/useEffect) for this example. Let’s look at the difference in detail below.
#### useLayoutEffect vs useEffect[Link for useLayoutEffect vs useEffect]()
1\. `useLayoutEffect` blocks the browser from repainting 2. `useEffect` does not block the browser
#### Example 1 of 2: `useLayoutEffect` blocks the browser from repainting[Link for this heading]()
React guarantees that the code inside `useLayoutEffect` and any state updates scheduled inside it will be processed **before the browser repaints the screen.** This lets you render the tooltip, measure it, and re-render the tooltip again without the user noticing the first extra render. In other words, `useLayoutEffect` blocks the browser from painting.
App.jsButtonWithTooltip.jsTooltip.jsTooltipContainer.js
Tooltip.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef, useLayoutEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import TooltipContainer from './TooltipContainer.js';
export default function Tooltip({ children, targetRect }) {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height);
}, []);
let tooltipX = 0;
let tooltipY = 0;
if (targetRect !== null) {
tooltipX = targetRect.left;
tooltipY = targetRect.top - tooltipHeight;
if (tooltipY < 0) {
// It doesn't fit above, so place below.
tooltipY = targetRect.bottom;
}
}
return createPortal(
<TooltipContainer x={tooltipX} y={tooltipY} contentRef={ref}>
{children}
</TooltipContainer>,
document.body
);
}
```
Show more
Next Example
### Note
Rendering in two passes and blocking the browser hurts performance. Try to avoid this when you can.
* * *
## Troubleshooting[Link for Troubleshooting]()
### I’m getting an error: “`useLayoutEffect` does nothing on the server”[Link for this heading]()
The purpose of `useLayoutEffect` is to let your component [use layout information for rendering:]()
1. Render the initial content.
2. Measure the layout *before the browser repaints the screen.*
3. Render the final content using the layout information you’ve read.
When you or your framework uses [server rendering](https://react.dev/reference/react-dom/server), your React app renders to HTML on the server for the initial render. This lets you show the initial HTML before the JavaScript code loads.
The problem is that on the server, there is no layout information.
In the [earlier example](), the `useLayoutEffect` call in the `Tooltip` component lets it position itself correctly (either above or below content) depending on the content height. If you tried to render `Tooltip` as a part of the initial server HTML, this would be impossible to determine. On the server, there is no layout yet! So, even if you rendered it on the server, its position would “jump” on the client after the JavaScript loads and runs.
Usually, components that rely on layout information don’t need to render on the server anyway. For example, it probably doesn’t make sense to show a `Tooltip` during the initial render. It is triggered by a client interaction.
However, if you’re running into this problem, you have a few different options:
- Replace `useLayoutEffect` with [`useEffect`.](https://react.dev/reference/react/useEffect) This tells React that it’s okay to display the initial render result without blocking the paint (because the original HTML will become visible before your Effect runs).
- Alternatively, [mark your component as client-only.](https://react.dev/reference/react/Suspense) This tells React to replace its content up to the closest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary with a loading fallback (for example, a spinner or a glimmer) during server rendering.
- Alternatively, you can render a component with `useLayoutEffect` only after hydration. Keep a boolean `isMounted` state that’s initialized to `false`, and set it to `true` inside a `useEffect` call. Your rendering logic can then be like `return isMounted ? <RealContent /> : <FallbackContent />`. On the server and during the hydration, the user will see `FallbackContent` which should not call `useLayoutEffect`. Then React will replace it with `RealContent` which runs on the client only and can include `useLayoutEffect` calls.
- If you synchronize your component with an external data store and rely on `useLayoutEffect` for different reasons than measuring layout, consider [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore) instead which [supports server rendering.](https://react.dev/reference/react/useSyncExternalStore)
[PrevioususeInsertionEffect](https://react.dev/reference/react/useInsertionEffect)
[NextuseMemo](https://react.dev/reference/react/useMemo) |
https://react.dev/reference/react/useEffect | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useEffect[Link for this heading]()
`useEffect` is a React Hook that lets you [synchronize a component with an external system.](https://react.dev/learn/synchronizing-with-effects)
```
useEffect(setup, dependencies?)
```
- [Reference]()
- [`useEffect(setup, dependencies?)`]()
- [Usage]()
- [Connecting to an external system]()
- [Wrapping Effects in custom Hooks]()
- [Controlling a non-React widget]()
- [Fetching data with Effects]()
- [Specifying reactive dependencies]()
- [Updating state based on previous state from an Effect]()
- [Removing unnecessary object dependencies]()
- [Removing unnecessary function dependencies]()
- [Reading the latest props and state from an Effect]()
- [Displaying different content on the server and the client]()
- [Troubleshooting]()
- [My Effect runs twice when the component mounts]()
- [My Effect runs after every re-render]()
- [My Effect keeps re-running in an infinite cycle]()
- [My cleanup logic runs even though my component didn’t unmount]()
- [My Effect does something visual, and I see a flicker before it runs]()
* * *
## Reference[Link for Reference]()
### `useEffect(setup, dependencies?)`[Link for this heading]()
Call `useEffect` at the top level of your component to declare an Effect:
```
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
// ...
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `setup`: The function with your Effect’s logic. Your setup function may also optionally return a *cleanup* function. When your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function.
- **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](https://react.dev/learn/editor-setup), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. If you omit this argument, your Effect will re-run after every re-render of the component. [See the difference between passing an array of dependencies, an empty array, and no dependencies at all.]()
#### Returns[Link for Returns]()
`useEffect` returns `undefined`.
#### Caveats[Link for Caveats]()
- `useEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
- If you’re **not trying to synchronize with some external system,** [you probably don’t need an Effect.](https://react.dev/learn/you-might-not-need-an-effect)
- When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic “mirrors” your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [implement the cleanup function.](https://react.dev/learn/synchronizing-with-effects)
- If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object]() and [function]() dependencies. You can also [extract state updates]() and [non-reactive logic]() outside of your Effect.
- If your Effect wasn’t caused by an interaction (like a click), React will generally let the browser **paint the updated screen first before running your Effect.** If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), replace `useEffect` with [`useLayoutEffect`.](https://react.dev/reference/react/useLayoutEffect)
- If your Effect is caused by an interaction (like a click), **React may run your Effect before the browser paints the updated screen**. This ensures that the result of the Effect can be observed by the event system. Usually, this works as expected. However, if you must defer the work until after paint, such as an `alert()`, you can use `setTimeout`. See [reactwg/react-18/128](https://github.com/reactwg/react-18/discussions/128) for more information.
- Even if your Effect was caused by an interaction (like a click), **React may allow the browser to repaint the screen before processing the state updates inside your Effect.** Usually, this works as expected. However, if you must block the browser from repainting the screen, you need to replace `useEffect` with [`useLayoutEffect`.](https://react.dev/reference/react/useLayoutEffect)
- Effects **only run on the client.** They don’t run during server rendering.
* * *
## Usage[Link for Usage]()
### Connecting to an external system[Link for Connecting to an external system]()
Some components need to stay connected to the network, some browser API, or a third-party library, while they are displayed on the page. These systems aren’t controlled by React, so they are called *external.*
To [connect your component to some external system,](https://react.dev/learn/synchronizing-with-effects) call `useEffect` at the top level of your component:
```
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
// ...
}
```
You need to pass two arguments to `useEffect`:
1. A *setup function* with setup code that connects to that system.
- It should return a *cleanup function* with cleanup code that disconnects from that system.
2. A list of dependencies including every value from your component used inside of those functions.
**React calls your setup and cleanup functions whenever it’s necessary, which may happen multiple times:**
1. Your setup code runs when your component is added to the page *(mounts)*.
2. After every re-render of your component where the dependencies have changed:
- First, your cleanup code runs with the old props and state.
- Then, your setup code runs with the new props and state.
3. Your cleanup code runs one final time after your component is removed from the page *(unmounts).*
**Let’s illustrate this sequence for the example above.**
When the `ChatRoom` component above gets added to the page, it will connect to the chat room with the initial `serverUrl` and `roomId`. If either `serverUrl` or `roomId` change as a result of a re-render (say, if the user picks a different chat room in a dropdown), your Effect will *disconnect from the previous room, and connect to the next one.* When the `ChatRoom` component is removed from the page, your Effect will disconnect one last time.
**To [help you find bugs,](https://react.dev/learn/synchronizing-with-effects) in development React runs setup and cleanup one extra time before the setup.** This is a stress-test that verifies your Effect’s logic is implemented correctly. If this causes visible issues, your cleanup function is missing some logic. The cleanup function should stop or undo whatever the setup function was doing. The rule of thumb is that the user shouldn’t be able to distinguish between the setup being called once (as in production) and a *setup* → *cleanup* → *setup* sequence (as in development). [See common solutions.](https://react.dev/learn/synchronizing-with-effects)
**Try to [write every Effect as an independent process](https://react.dev/learn/lifecycle-of-reactive-effects) and [think about a single setup/cleanup cycle at a time.](https://react.dev/learn/lifecycle-of-reactive-effects)** It shouldn’t matter whether your component is mounting, updating, or unmounting. When your cleanup logic correctly “mirrors” the setup logic, your Effect is resilient to running setup and cleanup as often as needed.
### Note
An Effect lets you [keep your component synchronized](https://react.dev/learn/synchronizing-with-effects) with some external system (like a chat service). Here, *external system* means any piece of code that’s not controlled by React, such as:
- A timer managed with [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) and [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval).
- An event subscription using [`window.addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) and [`window.removeEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener).
- A third-party animation library with an API like `animation.start()` and `animation.reset()`.
**If you’re not connecting to any external system, [you probably don’t need an Effect.](https://react.dev/learn/you-might-not-need-an-effect)**
#### Examples of connecting to an external system[Link for Examples of connecting to an external system]()
1\. Connecting to a chat server 2. Listening to a global browser event 3. Triggering an animation 4. Controlling a modal dialog 5. Tracking element visibility
#### Example 1 of 5: Connecting to a chat server[Link for this heading]()
In this example, the `ChatRoom` component uses an Effect to stay connected to an external system defined in `chat.js`. Press “Open chat” to make the `ChatRoom` component appear. This sandbox runs in development mode, so there is an extra connect-and-disconnect cycle, as [explained here.](https://react.dev/learn/synchronizing-with-effects) Try changing the `roomId` and `serverUrl` using the dropdown and the input, and see how the Effect re-connects to the chat. Press “Close chat” to see the Effect disconnect one last time.
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [roomId, serverUrl]);
return (
<>
<label>
Server URL:{' '}
<input
value={serverUrl}
onChange={e => setServerUrl(e.target.value)}
/>
</label>
<h1>Welcome to the {roomId} room!</h1>
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [show, setShow] = useState(false);
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<button onClick={() => setShow(!show)}>
{show ? 'Close chat' : 'Open chat'}
</button>
{show && <hr />}
{show && <ChatRoom roomId={roomId} />}
</>
);
}
```
Show more
Next Example
* * *
### Wrapping Effects in custom Hooks[Link for Wrapping Effects in custom Hooks]()
Effects are an [“escape hatch”:](https://react.dev/learn/escape-hatches) you use them when you need to “step outside React” and when there is no better built-in solution for your use case. If you find yourself often needing to manually write Effects, it’s usually a sign that you need to extract some [custom Hooks](https://react.dev/learn/reusing-logic-with-custom-hooks) for common behaviors your components rely on.
For example, this `useChatRoom` custom Hook “hides” the logic of your Effect behind a more declarative API:
```
function useChatRoom({ serverUrl, roomId }) {
useEffect(() => {
const options = {
serverUrl: serverUrl,
roomId: roomId
};
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId, serverUrl]);
}
```
Then you can use it from any component like this:
```
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useChatRoom({
roomId: roomId,
serverUrl: serverUrl
});
// ...
```
There are also many excellent custom Hooks for every purpose available in the React ecosystem.
[Learn more about wrapping Effects in custom Hooks.](https://react.dev/learn/reusing-logic-with-custom-hooks)
#### Examples of wrapping Effects in custom Hooks[Link for Examples of wrapping Effects in custom Hooks]()
1\. Custom `useChatRoom` Hook 2. Custom `useWindowListener` Hook 3. Custom `useIntersectionObserver` Hook
#### Example 1 of 3: Custom `useChatRoom` Hook[Link for this heading]()
This example is identical to one of the [earlier examples,]() but the logic is extracted to a custom Hook.
App.jsuseChatRoom.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
import { useChatRoom } from './useChatRoom.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useChatRoom({
roomId: roomId,
serverUrl: serverUrl
});
return (
<>
<label>
Server URL:{' '}
<input
value={serverUrl}
onChange={e => setServerUrl(e.target.value)}
/>
</label>
<h1>Welcome to the {roomId} room!</h1>
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [show, setShow] = useState(false);
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<button onClick={() => setShow(!show)}>
{show ? 'Close chat' : 'Open chat'}
</button>
{show && <hr />}
{show && <ChatRoom roomId={roomId} />}
</>
);
}
```
Show more
Next Example
* * *
### Controlling a non-React widget[Link for Controlling a non-React widget]()
Sometimes, you want to keep an external system synchronized to some prop or state of your component.
For example, if you have a third-party map widget or a video player component written without React, you can use an Effect to call methods on it that make its state match the current state of your React component. This Effect creates an instance of a `MapWidget` class defined in `map-widget.js`. When you change the `zoomLevel` prop of the `Map` component, the Effect calls the `setZoom()` on the class instance to keep it synchronized:
App.jsMap.jsmap-widget.js
Map.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef, useEffect } from 'react';
import { MapWidget } from './map-widget.js';
export default function Map({ zoomLevel }) {
const containerRef = useRef(null);
const mapRef = useRef(null);
useEffect(() => {
if (mapRef.current === null) {
mapRef.current = new MapWidget(containerRef.current);
}
const map = mapRef.current;
map.setZoom(zoomLevel);
}, [zoomLevel]);
return (
<div
style={{ width: 200, height: 200 }}
ref={containerRef}
/>
);
}
```
Show more
In this example, a cleanup function is not needed because the `MapWidget` class manages only the DOM node that was passed to it. After the `Map` React component is removed from the tree, both the DOM node and the `MapWidget` class instance will be automatically garbage-collected by the browser JavaScript engine.
* * *
### Fetching data with Effects[Link for Fetching data with Effects]()
You can use an Effect to fetch data for your component. Note that [if you use a framework,](https://react.dev/learn/start-a-new-react-project) using your framework’s data fetching mechanism will be a lot more efficient than writing Effects manually.
If you want to fetch data from an Effect manually, your code might look like this:
```
import { useState, useEffect } from 'react';
import { fetchBio } from './api.js';
export default function Page() {
const [person, setPerson] = useState('Alice');
const [bio, setBio] = useState(null);
useEffect(() => {
let ignore = false;
setBio(null);
fetchBio(person).then(result => {
if (!ignore) {
setBio(result);
}
});
return () => {
ignore = true;
};
}, [person]);
// ...
```
Note the `ignore` variable which is initialized to `false`, and is set to `true` during cleanup. This ensures [your code doesn’t suffer from “race conditions”:](https://maxrozen.com/race-conditions-fetching-data-react-with-useeffect) network responses may arrive in a different order than you sent them.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { fetchBio } from './api.js';
export default function Page() {
const [person, setPerson] = useState('Alice');
const [bio, setBio] = useState(null);
useEffect(() => {
let ignore = false;
setBio(null);
fetchBio(person).then(result => {
if (!ignore) {
setBio(result);
}
});
return () => {
ignore = true;
}
}, [person]);
return (
<>
<select value={person} onChange={e => {
setPerson(e.target.value);
}}>
<option value="Alice">Alice</option>
<option value="Bob">Bob</option>
<option value="Taylor">Taylor</option>
</select>
<hr />
<p><i>{bio ?? 'Loading...'}</i></p>
</>
);
}
```
Show more
You can also rewrite using the [`async` / `await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) syntax, but you still need to provide a cleanup function:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { fetchBio } from './api.js';
export default function Page() {
const [person, setPerson] = useState('Alice');
const [bio, setBio] = useState(null);
useEffect(() => {
async function startFetching() {
setBio(null);
const result = await fetchBio(person);
if (!ignore) {
setBio(result);
}
}
let ignore = false;
startFetching();
return () => {
ignore = true;
}
}, [person]);
return (
<>
<select value={person} onChange={e => {
setPerson(e.target.value);
}}>
<option value="Alice">Alice</option>
<option value="Bob">Bob</option>
<option value="Taylor">Taylor</option>
</select>
<hr />
<p><i>{bio ?? 'Loading...'}</i></p>
</>
);
}
```
Show more
Writing data fetching directly in Effects gets repetitive and makes it difficult to add optimizations like caching and server rendering later. [It’s easier to use a custom Hook—either your own or maintained by the community.](https://react.dev/learn/reusing-logic-with-custom-hooks)
##### Deep Dive
#### What are good alternatives to data fetching in Effects?[Link for What are good alternatives to data fetching in Effects?]()
Show Details
Writing `fetch` calls inside Effects is a [popular way to fetch data](https://www.robinwieruch.de/react-hooks-fetch-data/), especially in fully client-side apps. This is, however, a very manual approach and it has significant downsides:
- **Effects don’t run on the server.** This means that the initial server-rendered HTML will only include a loading state with no data. The client computer will have to download all JavaScript and render your app only to discover that now it needs to load the data. This is not very efficient.
- **Fetching directly in Effects makes it easy to create “network waterfalls”.** You render the parent component, it fetches some data, renders the child components, and then they start fetching their data. If the network is not very fast, this is significantly slower than fetching all data in parallel.
- **Fetching directly in Effects usually means you don’t preload or cache data.** For example, if the component unmounts and then mounts again, it would have to fetch the data again.
- **It’s not very ergonomic.** There’s quite a bit of boilerplate code involved when writing `fetch` calls in a way that doesn’t suffer from bugs like [race conditions.](https://maxrozen.com/race-conditions-fetching-data-react-with-useeffect)
This list of downsides is not specific to React. It applies to fetching data on mount with any library. Like with routing, data fetching is not trivial to do well, so we recommend the following approaches:
- **If you use a [framework](https://react.dev/learn/start-a-new-react-project), use its built-in data fetching mechanism.** Modern React frameworks have integrated data fetching mechanisms that are efficient and don’t suffer from the above pitfalls.
- **Otherwise, consider using or building a client-side cache.** Popular open source solutions include [React Query](https://tanstack.com/query/latest/), [useSWR](https://swr.vercel.app/), and [React Router 6.4+.](https://beta.reactrouter.com/en/main/start/overview) You can build your own solution too, in which case you would use Effects under the hood but also add logic for deduplicating requests, caching responses, and avoiding network waterfalls (by preloading data or hoisting data requirements to routes).
You can continue fetching data directly in Effects if neither of these approaches suit you.
* * *
### Specifying reactive dependencies[Link for Specifying reactive dependencies]()
**Notice that you can’t “choose” the dependencies of your Effect.** Every reactive value used by your Effect’s code must be declared as a dependency. Your Effect’s dependency list is determined by the surrounding code:
```
function ChatRoom({ roomId }) { // This is a reactive value
const [serverUrl, setServerUrl] = useState('https://localhost:1234'); // This is a reactive value too
useEffect(() => {
const connection = createConnection(serverUrl, roomId); // This Effect reads these reactive values
connection.connect();
return () => connection.disconnect();
}, [serverUrl, roomId]); // ✅ So you must specify them as dependencies of your Effect
// ...
}
```
If either `serverUrl` or `roomId` change, your Effect will reconnect to the chat using the new values.
**[Reactive values](https://react.dev/learn/lifecycle-of-reactive-effects) include props and all variables and functions declared directly inside of your component.** Since `roomId` and `serverUrl` are reactive values, you can’t remove them from the dependencies. If you try to omit them and [your linter is correctly configured for React,](https://react.dev/learn/editor-setup) the linter will flag this as a mistake you need to fix:
```
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, []); // 🔴 React Hook useEffect has missing dependencies: 'roomId' and 'serverUrl'
// ...
}
```
**To remove a dependency, you need to [“prove” to the linter that it *doesn’t need* to be a dependency.](https://react.dev/learn/removing-effect-dependencies)** For example, you can move `serverUrl` out of your component to prove that it’s not reactive and won’t change on re-renders:
```
const serverUrl = 'https://localhost:1234'; // Not a reactive value anymore
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ All dependencies declared
// ...
}
```
Now that `serverUrl` is not a reactive value (and can’t change on a re-render), it doesn’t need to be a dependency. **If your Effect’s code doesn’t use any reactive values, its dependency list should be empty (`[]`):**
```
const serverUrl = 'https://localhost:1234'; // Not a reactive value anymore
const roomId = 'music'; // Not a reactive value anymore
function ChatRoom() {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, []); // ✅ All dependencies declared
// ...
}
```
[An Effect with empty dependencies](https://react.dev/learn/lifecycle-of-reactive-effects) doesn’t re-run when any of your component’s props or state change.
### Pitfall
If you have an existing codebase, you might have some Effects that suppress the linter like this:
```
useEffect(() => {
// ...
// 🔴 Avoid suppressing the linter like this:
// eslint-ignore-next-line react-hooks/exhaustive-deps
}, []);
```
**When dependencies don’t match the code, there is a high risk of introducing bugs.** By suppressing the linter, you “lie” to React about the values your Effect depends on. [Instead, prove they’re unnecessary.](https://react.dev/learn/removing-effect-dependencies)
#### Examples of passing reactive dependencies[Link for Examples of passing reactive dependencies]()
1\. Passing a dependency array 2. Passing an empty dependency array 3. Passing no dependency array at all
#### Example 1 of 3: Passing a dependency array[Link for this heading]()
If you specify the dependencies, your Effect runs **after the initial render *and* after re-renders with changed dependencies.**
```
useEffect(() => {
// ...
}, [a, b]); // Runs again if a or b are different
```
In the below example, `serverUrl` and `roomId` are [reactive values,](https://react.dev/learn/lifecycle-of-reactive-effects) so they both must be specified as dependencies. As a result, selecting a different room in the dropdown or editing the server URL input causes the chat to re-connect. However, since `message` isn’t used in the Effect (and so it isn’t a dependency), editing the message doesn’t re-connect to the chat.
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
const [message, setMessage] = useState('');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
return (
<>
<label>
Server URL:{' '}
<input
value={serverUrl}
onChange={e => setServerUrl(e.target.value)}
/>
</label>
<h1>Welcome to the {roomId} room!</h1>
<label>
Your message:{' '}
<input value={message} onChange={e => setMessage(e.target.value)} />
</label>
</>
);
}
export default function App() {
const [show, setShow] = useState(false);
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
<button onClick={() => setShow(!show)}>
{show ? 'Close chat' : 'Open chat'}
</button>
</label>
{show && <hr />}
{show && <ChatRoom roomId={roomId}/>}
</>
);
}
```
Show more
Next Example
* * *
### Updating state based on previous state from an Effect[Link for Updating state based on previous state from an Effect]()
When you want to update state based on previous state from an Effect, you might run into a problem:
```
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCount(count + 1); // You want to increment the counter every second...
}, 1000)
return () => clearInterval(intervalId);
}, [count]); // 🚩 ... but specifying `count` as a dependency always resets the interval.
// ...
}
```
Since `count` is a reactive value, it must be specified in the list of dependencies. However, that causes the Effect to cleanup and setup again every time the `count` changes. This is not ideal.
To fix this, [pass the `c => c + 1` state updater](https://react.dev/reference/react/useState) to `setCount`:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCount(c => c + 1); // ✅ Pass a state updater
}, 1000);
return () => clearInterval(intervalId);
}, []); // ✅ Now count is not a dependency
return <h1>{count}</h1>;
}
```
Now that you’re passing `c => c + 1` instead of `count + 1`, [your Effect no longer needs to depend on `count`.](https://react.dev/learn/removing-effect-dependencies) As a result of this fix, it won’t need to cleanup and setup the interval again every time the `count` changes.
* * *
### Removing unnecessary object dependencies[Link for Removing unnecessary object dependencies]()
If your Effect depends on an object or a function created during rendering, it might run too often. For example, this Effect re-connects after every render because the `options` object is [different for every render:](https://react.dev/learn/removing-effect-dependencies)
```
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const options = { // 🚩 This object is created from scratch on every re-render
serverUrl: serverUrl,
roomId: roomId
};
useEffect(() => {
const connection = createConnection(options); // It's used inside the Effect
connection.connect();
return () => connection.disconnect();
}, [options]); // 🚩 As a result, these dependencies are always different on a re-render
// ...
```
Avoid using an object created during rendering as a dependency. Instead, create the object inside the Effect:
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
const options = {
serverUrl: serverUrl,
roomId: roomId
};
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return (
<>
<h1>Welcome to the {roomId} room!</h1>
<input value={message} onChange={e => setMessage(e.target.value)} />
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}
```
Show more
Now that you create the `options` object inside the Effect, the Effect itself only depends on the `roomId` string.
With this fix, typing into the input doesn’t reconnect the chat. Unlike an object which gets re-created, a string like `roomId` doesn’t change unless you set it to another value. [Read more about removing dependencies.](https://react.dev/learn/removing-effect-dependencies)
* * *
### Removing unnecessary function dependencies[Link for Removing unnecessary function dependencies]()
If your Effect depends on an object or a function created during rendering, it might run too often. For example, this Effect re-connects after every render because the `createOptions` function is [different for every render:](https://react.dev/learn/removing-effect-dependencies)
```
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
function createOptions() { // 🚩 This function is created from scratch on every re-render
return {
serverUrl: serverUrl,
roomId: roomId
};
}
useEffect(() => {
const options = createOptions(); // It's used inside the Effect
const connection = createConnection();
connection.connect();
return () => connection.disconnect();
}, [createOptions]); // 🚩 As a result, these dependencies are always different on a re-render
// ...
```
By itself, creating a function from scratch on every re-render is not a problem. You don’t need to optimize that. However, if you use it as a dependency of your Effect, it will cause your Effect to re-run after every re-render.
Avoid using a function created during rendering as a dependency. Instead, declare it inside the Effect:
App.jschat.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
function createOptions() {
return {
serverUrl: serverUrl,
roomId: roomId
};
}
const options = createOptions();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return (
<>
<h1>Welcome to the {roomId} room!</h1>
<input value={message} onChange={e => setMessage(e.target.value)} />
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}
```
Show more
Now that you define the `createOptions` function inside the Effect, the Effect itself only depends on the `roomId` string. With this fix, typing into the input doesn’t reconnect the chat. Unlike a function which gets re-created, a string like `roomId` doesn’t change unless you set it to another value. [Read more about removing dependencies.](https://react.dev/learn/removing-effect-dependencies)
* * *
### Reading the latest props and state from an Effect[Link for Reading the latest props and state from an Effect]()
### Under Construction
This section describes an **experimental API that has not yet been released** in a stable version of React.
By default, when you read a reactive value from an Effect, you have to add it as a dependency. This ensures that your Effect “reacts” to every change of that value. For most dependencies, that’s the behavior you want.
**However, sometimes you’ll want to read the *latest* props and state from an Effect without “reacting” to them.** For example, imagine you want to log the number of the items in the shopping cart for every page visit:
```
function Page({ url, shoppingCart }) {
useEffect(() => {
logVisit(url, shoppingCart.length);
}, [url, shoppingCart]); // ✅ All dependencies declared
// ...
}
```
**What if you want to log a new page visit after every `url` change, but *not* if only the `shoppingCart` changes?** You can’t exclude `shoppingCart` from dependencies without breaking the [reactivity rules.]() However, you can express that you *don’t want* a piece of code to “react” to changes even though it is called from inside an Effect. [Declare an *Effect Event*](https://react.dev/learn/separating-events-from-effects) with the [`useEffectEvent`](https://react.dev/reference/react/experimental_useEffectEvent) Hook, and move the code reading `shoppingCart` inside of it:
```
function Page({ url, shoppingCart }) {
const onVisit = useEffectEvent(visitedUrl => {
logVisit(visitedUrl, shoppingCart.length)
});
useEffect(() => {
onVisit(url);
}, [url]); // ✅ All dependencies declared
// ...
}
```
**Effect Events are not reactive and must always be omitted from dependencies of your Effect.** This is what lets you put non-reactive code (where you can read the latest value of some props and state) inside of them. By reading `shoppingCart` inside of `onVisit`, you ensure that `shoppingCart` won’t re-run your Effect.
[Read more about how Effect Events let you separate reactive and non-reactive code.](https://react.dev/learn/separating-events-from-effects)
* * *
### Displaying different content on the server and the client[Link for Displaying different content on the server and the client]()
If your app uses server rendering (either [directly](https://react.dev/reference/react-dom/server) or via a [framework](https://react.dev/learn/start-a-new-react-project)), your component will render in two different environments. On the server, it will render to produce the initial HTML. On the client, React will run the rendering code again so that it can attach your event handlers to that HTML. This is why, for [hydration](https://react.dev/reference/react-dom/client/hydrateRoot) to work, your initial render output must be identical on the client and the server.
In rare cases, you might need to display different content on the client. For example, if your app reads some data from [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), it can’t possibly do that on the server. Here is how you could implement this:
```
function MyComponent() {
const [didMount, setDidMount] = useState(false);
useEffect(() => {
setDidMount(true);
}, []);
if (didMount) {
// ... return client-only JSX ...
} else {
// ... return initial JSX ...
}
}
```
While the app is loading, the user will see the initial render output. Then, when it’s loaded and hydrated, your Effect will run and set `didMount` to `true`, triggering a re-render. This will switch to the client-only render output. Effects don’t run on the server, so this is why `didMount` was `false` during the initial server render.
Use this pattern sparingly. Keep in mind that users with a slow connection will see the initial content for quite a bit of time—potentially, many seconds—so you don’t want to make jarring changes to your component’s appearance. In many cases, you can avoid the need for this by conditionally showing different things with CSS.
* * *
## Troubleshooting[Link for Troubleshooting]()
### My Effect runs twice when the component mounts[Link for My Effect runs twice when the component mounts]()
When Strict Mode is on, in development, React runs setup and cleanup one extra time before the actual setup.
This is a stress-test that verifies your Effect’s logic is implemented correctly. If this causes visible issues, your cleanup function is missing some logic. The cleanup function should stop or undo whatever the setup function was doing. The rule of thumb is that the user shouldn’t be able to distinguish between the setup being called once (as in production) and a setup → cleanup → setup sequence (as in development).
Read more about [how this helps find bugs](https://react.dev/learn/synchronizing-with-effects) and [how to fix your logic.](https://react.dev/learn/synchronizing-with-effects)
* * *
### My Effect runs after every re-render[Link for My Effect runs after every re-render]()
First, check that you haven’t forgotten to specify the dependency array:
```
useEffect(() => {
// ...
}); // 🚩 No dependency array: re-runs after every render!
```
If you’ve specified the dependency array but your Effect still re-runs in a loop, it’s because one of your dependencies is different on every re-render.
You can debug this problem by manually logging your dependencies to the console:
```
useEffect(() => {
// ..
}, [serverUrl, roomId]);
console.log([serverUrl, roomId]);
```
You can then right-click on the arrays from different re-renders in the console and select “Store as a global variable” for both of them. Assuming the first one got saved as `temp1` and the second one got saved as `temp2`, you can then use the browser console to check whether each dependency in both arrays is the same:
```
Object.is(temp1[0], temp2[0]); // Is the first dependency the same between the arrays?
Object.is(temp1[1], temp2[1]); // Is the second dependency the same between the arrays?
Object.is(temp1[2], temp2[2]); // ... and so on for every dependency ...
```
When you find the dependency that is different on every re-render, you can usually fix it in one of these ways:
- [Updating state based on previous state from an Effect]()
- [Removing unnecessary object dependencies]()
- [Removing unnecessary function dependencies]()
- [Reading the latest props and state from an Effect]()
As a last resort (if these methods didn’t help), wrap its creation with [`useMemo`](https://react.dev/reference/react/useMemo) or [`useCallback`](https://react.dev/reference/react/useCallback) (for functions).
* * *
### My Effect keeps re-running in an infinite cycle[Link for My Effect keeps re-running in an infinite cycle]()
If your Effect runs in an infinite cycle, these two things must be true:
- Your Effect is updating some state.
- That state leads to a re-render, which causes the Effect’s dependencies to change.
Before you start fixing the problem, ask yourself whether your Effect is connecting to some external system (like DOM, network, a third-party widget, and so on). Why does your Effect need to set state? Does it synchronize with that external system? Or are you trying to manage your application’s data flow with it?
If there is no external system, consider whether [removing the Effect altogether](https://react.dev/learn/you-might-not-need-an-effect) would simplify your logic.
If you’re genuinely synchronizing with some external system, think about why and under what conditions your Effect should update the state. Has something changed that affects your component’s visual output? If you need to keep track of some data that isn’t used by rendering, a [ref](https://react.dev/reference/react/useRef) (which doesn’t trigger re-renders) might be more appropriate. Verify your Effect doesn’t update the state (and trigger re-renders) more than needed.
Finally, if your Effect is updating the state at the right time, but there is still a loop, it’s because that state update leads to one of the Effect’s dependencies changing. [Read how to debug dependency changes.](https://react.dev/reference/react/useEffect)
* * *
### My cleanup logic runs even though my component didn’t unmount[Link for My cleanup logic runs even though my component didn’t unmount]()
The cleanup function runs not only during unmount, but before every re-render with changed dependencies. Additionally, in development, React [runs setup+cleanup one extra time immediately after component mounts.]()
If you have cleanup code without corresponding setup code, it’s usually a code smell:
```
useEffect(() => {
// 🔴 Avoid: Cleanup logic without corresponding setup logic
return () => {
doSomething();
};
}, []);
```
Your cleanup logic should be “symmetrical” to the setup logic, and should stop or undo whatever setup did:
```
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
```
[Learn how the Effect lifecycle is different from the component’s lifecycle.](https://react.dev/learn/lifecycle-of-reactive-effects)
* * *
### My Effect does something visual, and I see a flicker before it runs[Link for My Effect does something visual, and I see a flicker before it runs]()
If your Effect must block the browser from [painting the screen,](https://react.dev/learn/render-and-commit) replace `useEffect` with [`useLayoutEffect`](https://react.dev/reference/react/useLayoutEffect). Note that **this shouldn’t be needed for the vast majority of Effects.** You’ll only need this if it’s crucial to run your Effect before the browser paint: for example, to measure and position a tooltip before the user sees it.
[PrevioususeDeferredValue](https://react.dev/reference/react/useDeferredValue)
[NextuseId](https://react.dev/reference/react/useId) |
https://react.dev/reference/react/useRef | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useRef[Link for this heading]()
`useRef` is a React Hook that lets you reference a value that’s not needed for rendering.
```
const ref = useRef(initialValue)
```
- [Reference]()
- [`useRef(initialValue)`]()
- [Usage]()
- [Referencing a value with a ref]()
- [Manipulating the DOM with a ref]()
- [Avoiding recreating the ref contents]()
- [Troubleshooting]()
- [I can’t get a ref to a custom component]()
* * *
## Reference[Link for Reference]()
### `useRef(initialValue)`[Link for this heading]()
Call `useRef` at the top level of your component to declare a [ref.](https://react.dev/learn/referencing-values-with-refs)
```
import { useRef } from 'react';
function MyComponent() {
const intervalRef = useRef(0);
const inputRef = useRef(null);
// ...
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `initialValue`: The value you want the ref object’s `current` property to be initially. It can be a value of any type. This argument is ignored after the initial render.
#### Returns[Link for Returns]()
`useRef` returns an object with a single property:
- `current`: Initially, it’s set to the `initialValue` you have passed. You can later set it to something else. If you pass the ref object to React as a `ref` attribute to a JSX node, React will set its `current` property.
On the next renders, `useRef` will return the same object.
#### Caveats[Link for Caveats]()
- You can mutate the `ref.current` property. Unlike state, it is mutable. However, if it holds an object that is used for rendering (for example, a piece of your state), then you shouldn’t mutate that object.
- When you change the `ref.current` property, React does not re-render your component. React is not aware of when you change it because a ref is a plain JavaScript object.
- Do not write *or read* `ref.current` during rendering, except for [initialization.]() This makes your component’s behavior unpredictable.
- In Strict Mode, React will **call your component function twice** in order to [help you find accidental impurities.](https://react.dev/reference/react/useState) This is development-only behavior and does not affect production. Each ref object will be created twice, but one of the versions will be discarded. If your component function is pure (as it should be), this should not affect the behavior.
* * *
## Usage[Link for Usage]()
### Referencing a value with a ref[Link for Referencing a value with a ref]()
Call `useRef` at the top level of your component to declare one or more [refs.](https://react.dev/learn/referencing-values-with-refs)
```
import { useRef } from 'react';
function Stopwatch() {
const intervalRef = useRef(0);
// ...
```
`useRef` returns a ref object with a single `current` property initially set to the initial value you provided.
On the next renders, `useRef` will return the same object. You can change its `current` property to store information and read it later. This might remind you of [state](https://react.dev/reference/react/useState), but there is an important difference.
**Changing a ref does not trigger a re-render.** This means refs are perfect for storing information that doesn’t affect the visual output of your component. For example, if you need to store an [interval ID](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its `current` property:
```
function handleStartClick() {
const intervalId = setInterval(() => {
// ...
}, 1000);
intervalRef.current = intervalId;
}
```
Later, you can read that interval ID from the ref so that you can call [clear that interval](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval):
```
function handleStopClick() {
const intervalId = intervalRef.current;
clearInterval(intervalId);
}
```
By using a ref, you ensure that:
- You can **store information** between re-renders (unlike regular variables, which reset on every render).
- Changing it **does not trigger a re-render** (unlike state variables, which trigger a re-render).
- The **information is local** to each copy of your component (unlike the variables outside, which are shared).
Changing a ref does not trigger a re-render, so refs are not appropriate for storing information you want to display on the screen. Use state for that instead. Read more about [choosing between `useRef` and `useState`.](https://react.dev/learn/referencing-values-with-refs)
#### Examples of referencing a value with useRef[Link for Examples of referencing a value with useRef]()
1\. Click counter 2. A stopwatch
#### Example 1 of 2: Click counter[Link for this heading]()
This component uses a ref to keep track of how many times the button was clicked. Note that it’s okay to use a ref instead of state here because the click count is only read and written in an event handler.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef } from 'react';
export default function Counter() {
let ref = useRef(0);
function handleClick() {
ref.current = ref.current + 1;
alert('You clicked ' + ref.current + ' times!');
}
return (
<button onClick={handleClick}>
Click me!
</button>
);
}
```
Show more
If you show `{ref.current}` in the JSX, the number won’t update on click. This is because setting `ref.current` does not trigger a re-render. Information that’s used for rendering should be state instead.
Next Example
### Pitfall
**Do not write *or read* `ref.current` during rendering.**
React expects that the body of your component [behaves like a pure function](https://react.dev/learn/keeping-components-pure):
- If the inputs ([props](https://react.dev/learn/passing-props-to-a-component), [state](https://react.dev/learn/state-a-components-memory), and [context](https://react.dev/learn/passing-data-deeply-with-context)) are the same, it should return exactly the same JSX.
- Calling it in a different order or with different arguments should not affect the results of other calls.
Reading or writing a ref **during rendering** breaks these expectations.
```
function MyComponent() {
// ...
// 🚩 Don't write a ref during rendering
myRef.current = 123;
// ...
// 🚩 Don't read a ref during rendering
return <h1>{myOtherRef.current}</h1>;
}
```
You can read or write refs **from event handlers or effects instead**.
```
function MyComponent() {
// ...
useEffect(() => {
// ✅ You can read or write refs in effects
myRef.current = 123;
});
// ...
function handleClick() {
// ✅ You can read or write refs in event handlers
doSomething(myOtherRef.current);
}
// ...
}
```
If you *have to* read [or write](https://react.dev/reference/react/useState) something during rendering, [use state](https://react.dev/reference/react/useState) instead.
When you break these rules, your component might still work, but most of the newer features we’re adding to React will rely on these expectations. Read more about [keeping your components pure.](https://react.dev/learn/keeping-components-pure)
* * *
### Manipulating the DOM with a ref[Link for Manipulating the DOM with a ref]()
It’s particularly common to use a ref to manipulate the [DOM.](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API) React has built-in support for this.
First, declare a ref object with an initial value of `null`:
```
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
// ...
```
Then pass your ref object as the `ref` attribute to the JSX of the DOM node you want to manipulate:
```
// ...
return <input ref={inputRef} />;
```
After React creates the DOM node and puts it on the screen, React will set the `current` property of your ref object to that DOM node. Now you can access the `<input>`’s DOM node and call methods like [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus):
```
function handleClick() {
inputRef.current.focus();
}
```
React will set the `current` property back to `null` when the node is removed from the screen.
Read more about [manipulating the DOM with refs.](https://react.dev/learn/manipulating-the-dom-with-refs)
#### Examples of manipulating the DOM with useRef[Link for Examples of manipulating the DOM with useRef]()
1\. Focusing a text input 2. Scrolling an image into view 3. Playing and pausing a video 4. Exposing a ref to your own component
#### Example 1 of 4: Focusing a text input[Link for this heading]()
In this example, clicking the button will focus the input:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>
Focus the input
</button>
</>
);
}
```
Show more
Next Example
* * *
### Avoiding recreating the ref contents[Link for Avoiding recreating the ref contents]()
React saves the initial ref value once and ignores it on the next renders.
```
function Video() {
const playerRef = useRef(new VideoPlayer());
// ...
```
Although the result of `new VideoPlayer()` is only used for the initial render, you’re still calling this function on every render. This can be wasteful if it’s creating expensive objects.
To solve it, you may initialize the ref like this instead:
```
function Video() {
const playerRef = useRef(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer();
}
// ...
```
Normally, writing or reading `ref.current` during render is not allowed. However, it’s fine in this case because the result is always the same, and the condition only executes during initialization so it’s fully predictable.
##### Deep Dive
#### How to avoid null checks when initializing useRef later[Link for How to avoid null checks when initializing useRef later]()
Show Details
If you use a type checker and don’t want to always check for `null`, you can try a pattern like this instead:
```
function Video() {
const playerRef = useRef(null);
function getPlayer() {
if (playerRef.current !== null) {
return playerRef.current;
}
const player = new VideoPlayer();
playerRef.current = player;
return player;
}
// ...
```
Here, the `playerRef` itself is nullable. However, you should be able to convince your type checker that there is no case in which `getPlayer()` returns `null`. Then use `getPlayer()` in your event handlers.
* * *
## Troubleshooting[Link for Troubleshooting]()
### I can’t get a ref to a custom component[Link for I can’t get a ref to a custom component]()
If you try to pass a `ref` to your own component like this:
```
const inputRef = useRef(null);
return <MyInput ref={inputRef} />;
```
You might get an error in the console:
Console
TypeError: Cannot read properties of null
By default, your own components don’t expose refs to the DOM nodes inside them.
To fix this, find the component that you want to get a ref to:
```
export default function MyInput({ value, onChange }) {
return (
<input
value={value}
onChange={onChange}
/>
);
}
```
And then add `ref` to the list of props your component accepts and pass `ref` as a prop to the relevent child [built-in component](https://react.dev/reference/react-dom/components/common) like this:
```
function MyInput({ value, onChange, ref }) {
return (
<input
value={value}
onChange={onChange}
ref={ref}
/>
);
};
export default MyInput;
```
Then the parent component can get a ref to it.
Read more about [accessing another component’s DOM nodes.](https://react.dev/learn/manipulating-the-dom-with-refs)
[PrevioususeReducer](https://react.dev/reference/react/useReducer)
[NextuseState](https://react.dev/reference/react/useState) |
https://react.dev/reference/react/useReducer | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useReducer[Link for this heading]()
`useReducer` is a React Hook that lets you add a [reducer](https://react.dev/learn/extracting-state-logic-into-a-reducer) to your component.
```
const [state, dispatch] = useReducer(reducer, initialArg, init?)
```
- [Reference]()
- [`useReducer(reducer, initialArg, init?)`]()
- [`dispatch` function]()
- [Usage]()
- [Adding a reducer to a component]()
- [Writing the reducer function]()
- [Avoiding recreating the initial state]()
- [Troubleshooting]()
- [I’ve dispatched an action, but logging gives me the old state value]()
- [I’ve dispatched an action, but the screen doesn’t update]()
- [A part of my reducer state becomes undefined after dispatching]()
- [My entire reducer state becomes undefined after dispatching]()
- [I’m getting an error: “Too many re-renders”]()
- [My reducer or initializer function runs twice]()
* * *
## Reference[Link for Reference]()
### `useReducer(reducer, initialArg, init?)`[Link for this heading]()
Call `useReducer` at the top level of your component to manage its state with a [reducer.](https://react.dev/learn/extracting-state-logic-into-a-reducer)
```
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `reducer`: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types.
- `initialArg`: The value from which the initial state is calculated. It can be a value of any type. How the initial state is calculated from it depends on the next `init` argument.
- **optional** `init`: The initializer function that should return the initial state. If it’s not specified, the initial state is set to `initialArg`. Otherwise, the initial state is set to the result of calling `init(initialArg)`.
#### Returns[Link for Returns]()
`useReducer` returns an array with exactly two values:
1. The current state. During the first render, it’s set to `init(initialArg)` or `initialArg` (if there’s no `init`).
2. The [`dispatch` function]() that lets you update the state to a different value and trigger a re-render.
#### Caveats[Link for Caveats]()
- `useReducer` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
- The `dispatch` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](https://react.dev/learn/removing-effect-dependencies)
- In Strict Mode, React will **call your reducer and initializer twice** in order to [help you find accidental impurities.]() This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect your logic. The result from one of the calls is ignored.
* * *
### `dispatch` function[Link for this heading]()
The `dispatch` function returned by `useReducer` lets you update the state to a different value and trigger a re-render. You need to pass the action as the only argument to the `dispatch` function:
```
const [state, dispatch] = useReducer(reducer, { age: 42 });
function handleClick() {
dispatch({ type: 'incremented_age' });
// ...
```
React will set the next state to the result of calling the `reducer` function you’ve provided with the current `state` and the action you’ve passed to `dispatch`.
#### Parameters[Link for Parameters]()
- `action`: The action performed by the user. It can be a value of any type. By convention, an action is usually an object with a `type` property identifying it and, optionally, other properties with additional information.
#### Returns[Link for Returns]()
`dispatch` functions do not have a return value.
#### Caveats[Link for Caveats]()
- The `dispatch` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `dispatch` function, [you will still get the old value]() that was on the screen before your call.
- If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. React may still need to call your component before ignoring the result, but it shouldn’t affect your code.
- React [batches state updates.](https://react.dev/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](https://react.dev/reference/react-dom/flushSync)
* * *
## Usage[Link for Usage]()
### Adding a reducer to a component[Link for Adding a reducer to a component]()
Call `useReducer` at the top level of your component to manage state with a [reducer.](https://react.dev/learn/extracting-state-logic-into-a-reducer)
```
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
```
`useReducer` returns an array with exactly two items:
1. The current state of this state variable, initially set to the initial state you provided.
2. The `dispatch` function that lets you change it in response to interaction.
To update what’s on the screen, call `dispatch` with an object representing what the user did, called an *action*:
```
function handleClick() {
dispatch({ type: 'incremented_age' });
}
```
React will pass the current state and the action to your reducer function. Your reducer will calculate and return the next state. React will store that next state, render your component with it, and update the UI.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useReducer } from 'react';
function reducer(state, action) {
if (action.type === 'incremented_age') {
return {
age: state.age + 1
};
}
throw Error('Unknown action.');
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
return (
<>
<button onClick={() => {
dispatch({ type: 'incremented_age' })
}}>
Increment age
</button>
<p>Hello! You are {state.age}.</p>
</>
);
}
```
Show more
`useReducer` is very similar to [`useState`](https://react.dev/reference/react/useState), but it lets you move the state update logic from event handlers into a single function outside of your component. Read more about [choosing between `useState` and `useReducer`.](https://react.dev/learn/extracting-state-logic-into-a-reducer)
* * *
### Writing the reducer function[Link for Writing the reducer function]()
A reducer function is declared like this:
```
function reducer(state, action) {
// ...
}
```
Then you need to fill in the code that will calculate and return the next state. By convention, it is common to write it as a [`switch` statement.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) For each `case` in the `switch`, calculate and return some next state.
```
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
return {
name: state.name,
age: state.age + 1
};
}
case 'changed_name': {
return {
name: action.nextName,
age: state.age
};
}
}
throw Error('Unknown action: ' + action.type);
}
```
Actions can have any shape. By convention, it’s common to pass objects with a `type` property identifying the action. It should include the minimal necessary information that the reducer needs to compute the next state.
```
function Form() {
const [state, dispatch] = useReducer(reducer, { name: 'Taylor', age: 42 });
function handleButtonClick() {
dispatch({ type: 'incremented_age' });
}
function handleInputChange(e) {
dispatch({
type: 'changed_name',
nextName: e.target.value
});
}
// ...
```
The action type names are local to your component. [Each action describes a single interaction, even if that leads to multiple changes in data.](https://react.dev/learn/extracting-state-logic-into-a-reducer) The shape of the state is arbitrary, but usually it’ll be an object or an array.
Read [extracting state logic into a reducer](https://react.dev/learn/extracting-state-logic-into-a-reducer) to learn more.
### Pitfall
State is read-only. Don’t modify any objects or arrays in state:
```
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// 🚩 Don't mutate an object in state like this:
state.age = state.age + 1;
return state;
}
```
Instead, always return new objects from your reducer:
```
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ✅ Instead, return a new object
return {
...state,
age: state.age + 1
};
}
```
Read [updating objects in state](https://react.dev/learn/updating-objects-in-state) and [updating arrays in state](https://react.dev/learn/updating-arrays-in-state) to learn more.
#### Basic useReducer examples[Link for Basic useReducer examples]()
1\. Form (object) 2. Todo list (array) 3. Writing concise update logic with Immer
#### Example 1 of 3: Form (object)[Link for this heading]()
In this example, the reducer manages a state object with two fields: `name` and `age`.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
return {
name: state.name,
age: state.age + 1
};
}
case 'changed_name': {
return {
name: action.nextName,
age: state.age
};
}
}
throw Error('Unknown action: ' + action.type);
}
const initialState = { name: 'Taylor', age: 42 };
export default function Form() {
const [state, dispatch] = useReducer(reducer, initialState);
function handleButtonClick() {
dispatch({ type: 'incremented_age' });
}
function handleInputChange(e) {
dispatch({
type: 'changed_name',
nextName: e.target.value
});
}
return (
<>
<input
value={state.name}
onChange={handleInputChange}
/>
<button onClick={handleButtonClick}>
Increment age
</button>
<p>Hello, {state.name}. You are {state.age}.</p>
</>
);
}
```
Show more
Next Example
* * *
### Avoiding recreating the initial state[Link for Avoiding recreating the initial state]()
React saves the initial state once and ignores it on the next renders.
```
function createInitialState(username) {
// ...
}
function TodoList({ username }) {
const [state, dispatch] = useReducer(reducer, createInitialState(username));
// ...
```
Although the result of `createInitialState(username)` is only used for the initial render, you’re still calling this function on every render. This can be wasteful if it’s creating large arrays or performing expensive calculations.
To solve this, you may **pass it as an *initializer* function** to `useReducer` as the third argument instead:
```
function createInitialState(username) {
// ...
}
function TodoList({ username }) {
const [state, dispatch] = useReducer(reducer, username, createInitialState);
// ...
```
Notice that you’re passing `createInitialState`, which is the *function itself*, and not `createInitialState()`, which is the result of calling it. This way, the initial state does not get re-created after initialization.
In the above example, `createInitialState` takes a `username` argument. If your initializer doesn’t need any information to compute the initial state, you may pass `null` as the second argument to `useReducer`.
#### The difference between passing an initializer and passing the initial state directly[Link for The difference between passing an initializer and passing the initial state directly]()
1\. Passing the initializer function 2. Passing the initial state directly
#### Example 1 of 2: Passing the initializer function[Link for this heading]()
This example passes the initializer function, so the `createInitialState` function only runs during initialization. It does not run when component re-renders, such as when you type into the input.
TodoList.js
TodoList.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useReducer } from 'react';
function createInitialState(username) {
const initialTodos = [];
for (let i = 0; i < 50; i++) {
initialTodos.push({
id: i,
text: username + "'s task #" + (i + 1)
});
}
return {
draft: '',
todos: initialTodos,
};
}
function reducer(state, action) {
switch (action.type) {
case 'changed_draft': {
return {
draft: action.nextDraft,
todos: state.todos,
};
};
case 'added_todo': {
return {
draft: '',
todos: [{
id: state.todos.length,
text: state.draft
}, ...state.todos]
}
}
}
throw Error('Unknown action: ' + action.type);
}
export default function TodoList({ username }) {
const [state, dispatch] = useReducer(
reducer,
username,
createInitialState
);
return (
<>
<input
value={state.draft}
onChange={e => {
dispatch({
type: 'changed_draft',
nextDraft: e.target.value
})
}}
/>
<button onClick={() => {
dispatch({ type: 'added_todo' });
}}>Add</button>
<ul>
{state.todos.map(item => (
<li key={item.id}>
{item.text}
</li>
))}
</ul>
</>
);
}
```
Show more
Next Example
* * *
## Troubleshooting[Link for Troubleshooting]()
### I’ve dispatched an action, but logging gives me the old state value[Link for I’ve dispatched an action, but logging gives me the old state value]()
Calling the `dispatch` function **does not change state in the running code**:
```
function handleClick() {
console.log(state.age); // 42
dispatch({ type: 'incremented_age' }); // Request a re-render with 43
console.log(state.age); // Still 42!
setTimeout(() => {
console.log(state.age); // Also 42!
}, 5000);
}
```
This is because [states behaves like a snapshot.](https://react.dev/learn/state-as-a-snapshot) Updating state requests another render with the new state value, but does not affect the `state` JavaScript variable in your already-running event handler.
If you need to guess the next state value, you can calculate it manually by calling the reducer yourself:
```
const action = { type: 'incremented_age' };
dispatch(action);
const nextState = reducer(state, action);
console.log(state); // { age: 42 }
console.log(nextState); // { age: 43 }
```
* * *
### I’ve dispatched an action, but the screen doesn’t update[Link for I’ve dispatched an action, but the screen doesn’t update]()
React will **ignore your update if the next state is equal to the previous state,** as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. This usually happens when you change an object or an array in state directly:
```
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// 🚩 Wrong: mutating existing object
state.age++;
return state;
}
case 'changed_name': {
// 🚩 Wrong: mutating existing object
state.name = action.nextName;
return state;
}
// ...
}
}
```
You mutated an existing `state` object and returned it, so React ignored the update. To fix this, you need to ensure that you’re always [updating objects in state](https://react.dev/learn/updating-objects-in-state) and [updating arrays in state](https://react.dev/learn/updating-arrays-in-state) instead of mutating them:
```
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ✅ Correct: creating a new object
return {
...state,
age: state.age + 1
};
}
case 'changed_name': {
// ✅ Correct: creating a new object
return {
...state,
name: action.nextName
};
}
// ...
}
}
```
* * *
### A part of my reducer state becomes undefined after dispatching[Link for A part of my reducer state becomes undefined after dispatching]()
Make sure that every `case` branch **copies all of the existing fields** when returning the new state:
```
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
return {
...state, // Don't forget this!
age: state.age + 1
};
}
// ...
```
Without `...state` above, the returned next state would only contain the `age` field and nothing else.
* * *
### My entire reducer state becomes undefined after dispatching[Link for My entire reducer state becomes undefined after dispatching]()
If your state unexpectedly becomes `undefined`, you’re likely forgetting to `return` state in one of the cases, or your action type doesn’t match any of the `case` statements. To find why, throw an error outside the `switch`:
```
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ...
}
case 'edited_name': {
// ...
}
}
throw Error('Unknown action: ' + action.type);
}
```
You can also use a static type checker like TypeScript to catch such mistakes.
* * *
### I’m getting an error: “Too many re-renders”[Link for I’m getting an error: “Too many re-renders”]()
You might get an error that says: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Typically, this means that you’re unconditionally dispatching an action *during render*, so your component enters a loop: render, dispatch (which causes a render), render, dispatch (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler:
```
// 🚩 Wrong: calls the handler during render
return <button onClick={handleClick()}>Click me</button>
// ✅ Correct: passes down the event handler
return <button onClick={handleClick}>Click me</button>
// ✅ Correct: passes down an inline function
return <button onClick={(e) => handleClick(e)}>Click me</button>
```
If you can’t find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `dispatch` function call responsible for the error.
* * *
### My reducer or initializer function runs twice[Link for My reducer or initializer function runs twice]()
In [Strict Mode](https://react.dev/reference/react/StrictMode), React will call your reducer and initializer functions twice. This shouldn’t break your code.
This **development-only** behavior helps you [keep components pure.](https://react.dev/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and reducer functions are pure, this shouldn’t affect your logic. However, if they are accidentally impure, this helps you notice the mistakes.
For example, this impure reducer function mutates an array in state:
```
function reducer(state, action) {
switch (action.type) {
case 'added_todo': {
// 🚩 Mistake: mutating state
state.todos.push({ id: nextId++, text: action.text });
return state;
}
// ...
}
}
```
Because React calls your reducer function twice, you’ll see the todo was added twice, so you’ll know that there is a mistake. In this example, you can fix the mistake by [replacing the array instead of mutating it](https://react.dev/learn/updating-arrays-in-state):
```
function reducer(state, action) {
switch (action.type) {
case 'added_todo': {
// ✅ Correct: replacing with new state
return {
...state,
todos: [
...state.todos,
{ id: nextId++, text: action.text }
]
};
}
// ...
}
}
```
Now that this reducer function is pure, calling it an extra time doesn’t make a difference in behavior. This is why React calling it twice helps you find mistakes. **Only component, initializer, and reducer functions need to be pure.** Event handlers don’t need to be pure, so React will never call your event handlers twice.
Read [keeping components pure](https://react.dev/learn/keeping-components-pure) to learn more.
[PrevioususeOptimistic](https://react.dev/reference/react/useOptimistic)
[NextuseRef](https://react.dev/reference/react/useRef) |
https://react.dev/reference/react/useState | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useState[Link for this heading]()
`useState` is a React Hook that lets you add a [state variable](https://react.dev/learn/state-a-components-memory) to your component.
```
const [state, setState] = useState(initialState)
```
- [Reference]()
- [`useState(initialState)`]()
- [`set` functions, like `setSomething(nextState)`]()
- [Usage]()
- [Adding state to a component]()
- [Updating state based on the previous state]()
- [Updating objects and arrays in state]()
- [Avoiding recreating the initial state]()
- [Resetting state with a key]()
- [Storing information from previous renders]()
- [Troubleshooting]()
- [I’ve updated the state, but logging gives me the old value]()
- [I’ve updated the state, but the screen doesn’t update]()
- [I’m getting an error: “Too many re-renders”]()
- [My initializer or updater function runs twice]()
- [I’m trying to set state to a function, but it gets called instead]()
* * *
## Reference[Link for Reference]()
### `useState(initialState)`[Link for this heading]()
Call `useState` at the top level of your component to declare a [state variable.](https://react.dev/learn/state-a-components-memory)
```
import { useState } from 'react';
function MyComponent() {
const [age, setAge] = useState(28);
const [name, setName] = useState('Taylor');
const [todos, setTodos] = useState(() => createTodos());
// ...
```
The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment)
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render.
- If you pass a function as `initialState`, it will be treated as an *initializer function*. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. [See an example below.]()
#### Returns[Link for Returns]()
`useState` returns an array with exactly two values:
1. The current state. During the first render, it will match the `initialState` you have passed.
2. The [`set` function]() that lets you update the state to a different value and trigger a re-render.
#### Caveats[Link for Caveats]()
- `useState` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
- In Strict Mode, React will **call your initializer function twice** in order to [help you find accidental impurities.]() This is development-only behavior and does not affect production. If your initializer function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.
* * *
### `set` functions, like `setSomething(nextState)`[Link for this heading]()
The `set` function returned by `useState` lets you update the state to a different value and trigger a re-render. You can pass the next state directly, or a function that calculates it from the previous state:
```
const [name, setName] = useState('Edward');
function handleClick() {
setName('Taylor');
setAge(a => a + 1);
// ...
```
#### Parameters[Link for Parameters]()
- `nextState`: The value that you want the state to be. It can be a value of any type, but there is a special behavior for functions.
- If you pass a function as `nextState`, it will be treated as an *updater function*. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. [See an example below.]()
#### Returns[Link for Returns]()
`set` functions do not have a return value.
#### Caveats[Link for Caveats]()
- The `set` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `set` function, [you will still get the old value]() that was on the screen before your call.
- If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn’t affect your code.
- React [batches state updates.](https://react.dev/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](https://react.dev/reference/react-dom/flushSync)
- The `set` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](https://react.dev/learn/removing-effect-dependencies)
- Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example below.]()
- In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.]() This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.
* * *
## Usage[Link for Usage]()
### Adding state to a component[Link for Adding state to a component]()
Call `useState` at the top level of your component to declare one or more [state variables.](https://react.dev/learn/state-a-components-memory)
```
import { useState } from 'react';
function MyComponent() {
const [age, setAge] = useState(42);
const [name, setName] = useState('Taylor');
// ...
```
The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment)
`useState` returns an array with exactly two items:
1. The current state of this state variable, initially set to the initial state you provided.
2. The `set` function that lets you change it to any other value in response to interaction.
To update what’s on the screen, call the `set` function with some next state:
```
function handleClick() {
setName('Robin');
}
```
React will store the next state, render your component again with the new values, and update the UI.
### Pitfall
Calling the `set` function [**does not** change the current state in the already executing code]():
```
function handleClick() {
setName('Robin');
console.log(name); // Still "Taylor"!
}
```
It only affects what `useState` will return starting from the *next* render.
#### Basic useState examples[Link for Basic useState examples]()
1\. Counter (number) 2. Text field (string) 3. Checkbox (boolean) 4. Form (two variables)
#### Example 1 of 4: Counter (number)[Link for this heading]()
In this example, the `count` state variable holds a number. Clicking the button increments it.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
You pressed me {count} times
</button>
);
}
```
Next Example
* * *
### Updating state based on the previous state[Link for Updating state based on the previous state]()
Suppose the `age` is `42`. This handler calls `setAge(age + 1)` three times:
```
function handleClick() {
setAge(age + 1); // setAge(42 + 1)
setAge(age + 1); // setAge(42 + 1)
setAge(age + 1); // setAge(42 + 1)
}
```
However, after one click, `age` will only be `43` rather than `45`! This is because calling the `set` function [does not update](https://react.dev/learn/state-as-a-snapshot) the `age` state variable in the already running code. So each `setAge(age + 1)` call becomes `setAge(43)`.
To solve this problem, **you may pass an *updater function*** to `setAge` instead of the next state:
```
function handleClick() {
setAge(a => a + 1); // setAge(42 => 43)
setAge(a => a + 1); // setAge(43 => 44)
setAge(a => a + 1); // setAge(44 => 45)
}
```
Here, `a => a + 1` is your updater function. It takes the pending state and calculates the next state from it.
React puts your updater functions in a [queue.](https://react.dev/learn/queueing-a-series-of-state-updates) Then, during the next render, it will call them in the same order:
1. `a => a + 1` will receive `42` as the pending state and return `43` as the next state.
2. `a => a + 1` will receive `43` as the pending state and return `44` as the next state.
3. `a => a + 1` will receive `44` as the pending state and return `45` as the next state.
There are no other queued updates, so React will store `45` as the current state in the end.
By convention, it’s common to name the pending state argument for the first letter of the state variable name, like `a` for `age`. However, you may also call it like `prevAge` or something else that you find clearer.
React may [call your updaters twice]() in development to verify that they are [pure.](https://react.dev/learn/keeping-components-pure)
##### Deep Dive
#### Is using an updater always preferred?[Link for Is using an updater always preferred?]()
Show Details
You might hear a recommendation to always write code like `setAge(a => a + 1)` if the state you’re setting is calculated from the previous state. There is no harm in it, but it is also not always necessary.
In most cases, there is no difference between these two approaches. React always makes sure that for intentional user actions, like clicks, the `age` state variable would be updated before the next click. This means there is no risk of a click handler seeing a “stale” `age` at the beginning of the event handler.
However, if you do multiple updates within the same event, updaters can be helpful. They’re also helpful if accessing the state variable itself is inconvenient (you might run into this when optimizing re-renders).
If you prefer consistency over slightly more verbose syntax, it’s reasonable to always write an updater if the state you’re setting is calculated from the previous state. If it’s calculated from the previous state of some *other* state variable, you might want to combine them into one object and [use a reducer.](https://react.dev/learn/extracting-state-logic-into-a-reducer)
#### The difference between passing an updater and passing the next state directly[Link for The difference between passing an updater and passing the next state directly]()
1\. Passing the updater function 2. Passing the next state directly
#### Example 1 of 2: Passing the updater function[Link for this heading]()
This example passes the updater function, so the “+3” button works.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Counter() {
const [age, setAge] = useState(42);
function increment() {
setAge(a => a + 1);
}
return (
<>
<h1>Your age: {age}</h1>
<button onClick={() => {
increment();
increment();
increment();
}}>+3</button>
<button onClick={() => {
increment();
}}>+1</button>
</>
);
}
```
Show more
Next Example
* * *
### Updating objects and arrays in state[Link for Updating objects and arrays in state]()
You can put objects and arrays into state. In React, state is considered read-only, so **you should *replace* it rather than *mutate* your existing objects**. For example, if you have a `form` object in state, don’t mutate it:
```
// 🚩 Don't mutate an object in state like this:
form.firstName = 'Taylor';
```
Instead, replace the whole object by creating a new one:
```
// ✅ Replace state with a new object
setForm({
...form,
firstName: 'Taylor'
});
```
Read [updating objects in state](https://react.dev/learn/updating-objects-in-state) and [updating arrays in state](https://react.dev/learn/updating-arrays-in-state) to learn more.
#### Examples of objects and arrays in state[Link for Examples of objects and arrays in state]()
1\. Form (object) 2. Form (nested object) 3. List (array) 4. Writing concise update logic with Immer
#### Example 1 of 4: Form (object)[Link for this heading]()
In this example, the `form` state variable holds an object. Each input has a change handler that calls `setForm` with the next state of the entire form. The `{ ...form }` spread syntax ensures that the state object is replaced rather than mutated.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Form() {
const [form, setForm] = useState({
firstName: 'Barbara',
lastName: 'Hepworth',
email: '[email protected]',
});
return (
<>
<label>
First name:
<input
value={form.firstName}
onChange={e => {
setForm({
...form,
firstName: e.target.value
});
}}
/>
</label>
<label>
Last name:
<input
value={form.lastName}
onChange={e => {
setForm({
...form,
lastName: e.target.value
});
}}
/>
</label>
<label>
Email:
<input
value={form.email}
onChange={e => {
setForm({
...form,
email: e.target.value
});
}}
/>
</label>
<p>
{form.firstName}{' '}
{form.lastName}{' '}
({form.email})
</p>
</>
);
}
```
Show more
Next Example
* * *
### Avoiding recreating the initial state[Link for Avoiding recreating the initial state]()
React saves the initial state once and ignores it on the next renders.
```
function TodoList() {
const [todos, setTodos] = useState(createInitialTodos());
// ...
```
Although the result of `createInitialTodos()` is only used for the initial render, you’re still calling this function on every render. This can be wasteful if it’s creating large arrays or performing expensive calculations.
To solve this, you may **pass it as an *initializer* function** to `useState` instead:
```
function TodoList() {
const [todos, setTodos] = useState(createInitialTodos);
// ...
```
Notice that you’re passing `createInitialTodos`, which is the *function itself*, and not `createInitialTodos()`, which is the result of calling it. If you pass a function to `useState`, React will only call it during initialization.
React may [call your initializers twice]() in development to verify that they are [pure.](https://react.dev/learn/keeping-components-pure)
#### The difference between passing an initializer and passing the initial state directly[Link for The difference between passing an initializer and passing the initial state directly]()
1\. Passing the initializer function 2. Passing the initial state directly
#### Example 1 of 2: Passing the initializer function[Link for this heading]()
This example passes the initializer function, so the `createInitialTodos` function only runs during initialization. It does not run when component re-renders, such as when you type into the input.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
function createInitialTodos() {
const initialTodos = [];
for (let i = 0; i < 50; i++) {
initialTodos.push({
id: i,
text: 'Item ' + (i + 1)
});
}
return initialTodos;
}
export default function TodoList() {
const [todos, setTodos] = useState(createInitialTodos);
const [text, setText] = useState('');
return (
<>
<input
value={text}
onChange={e => setText(e.target.value)}
/>
<button onClick={() => {
setText('');
setTodos([{
id: todos.length,
text: text
}, ...todos]);
}}>Add</button>
<ul>
{todos.map(item => (
<li key={item.id}>
{item.text}
</li>
))}
</ul>
</>
);
}
```
Show more
Next Example
* * *
### Resetting state with a key[Link for Resetting state with a key]()
You’ll often encounter the `key` attribute when [rendering lists.](https://react.dev/learn/rendering-lists) However, it also serves another purpose.
You can **reset a component’s state by passing a different `key` to a component.** In this example, the Reset button changes the `version` state variable, which we pass as a `key` to the `Form`. When the `key` changes, React re-creates the `Form` component (and all of its children) from scratch, so its state gets reset.
Read [preserving and resetting state](https://react.dev/learn/preserving-and-resetting-state) to learn more.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function App() {
const [version, setVersion] = useState(0);
function handleReset() {
setVersion(version + 1);
}
return (
<>
<button onClick={handleReset}>Reset</button>
<Form key={version} />
</>
);
}
function Form() {
const [name, setName] = useState('Taylor');
return (
<>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<p>Hello, {name}.</p>
</>
);
}
```
Show more
* * *
### Storing information from previous renders[Link for Storing information from previous renders]()
Usually, you will update state in event handlers. However, in rare cases you might want to adjust state in response to rendering — for example, you might want to change a state variable when a prop changes.
In most cases, you don’t need this:
- **If the value you need can be computed entirely from the current props or other state, [remove that redundant state altogether.](https://react.dev/learn/choosing-the-state-structure)** If you’re worried about recomputing too often, the [`useMemo` Hook](https://react.dev/reference/react/useMemo) can help.
- If you want to reset the entire component tree’s state, [pass a different `key` to your component.]()
- If you can, update all the relevant state in the event handlers.
In the rare case that none of these apply, there is a pattern you can use to update state based on the values that have been rendered so far, by calling a `set` function while your component is rendering.
Here’s an example. This `CountLabel` component displays the `count` prop passed to it:
```
export default function CountLabel({ count }) {
return <h1>{count}</h1>
}
```
Say you want to show whether the counter has *increased or decreased* since the last change. The `count` prop doesn’t tell you this — you need to keep track of its previous value. Add the `prevCount` state variable to track it. Add another state variable called `trend` to hold whether the count has increased or decreased. Compare `prevCount` with `count`, and if they’re not equal, update both `prevCount` and `trend`. Now you can show both the current count prop and *how it has changed since the last render*.
App.jsCountLabel.js
CountLabel.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function CountLabel({ count }) {
const [prevCount, setPrevCount] = useState(count);
const [trend, setTrend] = useState(null);
if (prevCount !== count) {
setPrevCount(count);
setTrend(count > prevCount ? 'increasing' : 'decreasing');
}
return (
<>
<h1>{count}</h1>
{trend && <p>The count is {trend}</p>}
</>
);
}
```
Show more
Note that if you call a `set` function while rendering, it must be inside a condition like `prevCount !== count`, and there must be a call like `setPrevCount(count)` inside of the condition. Otherwise, your component would re-render in a loop until it crashes. Also, you can only update the state of the *currently rendering* component like this. Calling the `set` function of *another* component during rendering is an error. Finally, your `set` call should still [update state without mutation]() — this doesn’t mean you can break other rules of [pure functions.](https://react.dev/learn/keeping-components-pure)
This pattern can be hard to understand and is usually best avoided. However, it’s better than updating state in an effect. When you call the `set` function during render, React will re-render that component immediately after your component exits with a `return` statement, and before rendering the children. This way, children don’t need to render twice. The rest of your component function will still execute (and the result will be thrown away). If your condition is below all the Hook calls, you may add an early `return;` to restart rendering earlier.
* * *
## Troubleshooting[Link for Troubleshooting]()
### I’ve updated the state, but logging gives me the old value[Link for I’ve updated the state, but logging gives me the old value]()
Calling the `set` function **does not change state in the running code**:
```
function handleClick() {
console.log(count); // 0
setCount(count + 1); // Request a re-render with 1
console.log(count); // Still 0!
setTimeout(() => {
console.log(count); // Also 0!
}, 5000);
}
```
This is because [states behaves like a snapshot.](https://react.dev/learn/state-as-a-snapshot) Updating state requests another render with the new state value, but does not affect the `count` JavaScript variable in your already-running event handler.
If you need to use the next state, you can save it in a variable before passing it to the `set` function:
```
const nextCount = count + 1;
setCount(nextCount);
console.log(count); // 0
console.log(nextCount); // 1
```
* * *
### I’ve updated the state, but the screen doesn’t update[Link for I’ve updated the state, but the screen doesn’t update]()
React will **ignore your update if the next state is equal to the previous state,** as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. This usually happens when you change an object or an array in state directly:
```
obj.x = 10; // 🚩 Wrong: mutating existing object
setObj(obj); // 🚩 Doesn't do anything
```
You mutated an existing `obj` object and passed it back to `setObj`, so React ignored the update. To fix this, you need to ensure that you’re always [*replacing* objects and arrays in state instead of *mutating* them]():
```
// ✅ Correct: creating a new object
setObj({
...obj,
x: 10
});
```
* * *
### I’m getting an error: “Too many re-renders”[Link for I’m getting an error: “Too many re-renders”]()
You might get an error that says: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Typically, this means that you’re unconditionally setting state *during render*, so your component enters a loop: render, set state (which causes a render), render, set state (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler:
```
// 🚩 Wrong: calls the handler during render
return <button onClick={handleClick()}>Click me</button>
// ✅ Correct: passes down the event handler
return <button onClick={handleClick}>Click me</button>
// ✅ Correct: passes down an inline function
return <button onClick={(e) => handleClick(e)}>Click me</button>
```
If you can’t find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `set` function call responsible for the error.
* * *
### My initializer or updater function runs twice[Link for My initializer or updater function runs twice]()
In [Strict Mode](https://react.dev/reference/react/StrictMode), React will call some of your functions twice instead of once:
```
function TodoList() {
// This component function will run twice for every render.
const [todos, setTodos] = useState(() => {
// This initializer function will run twice during initialization.
return createTodos();
});
function handleClick() {
setTodos(prevTodos => {
// This updater function will run twice for every click.
return [...prevTodos, createTodo()];
});
}
// ...
```
This is expected and shouldn’t break your code.
This **development-only** behavior helps you [keep components pure.](https://react.dev/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and updater functions are pure, this shouldn’t affect your logic. However, if they are accidentally impure, this helps you notice the mistakes.
For example, this impure updater function mutates an array in state:
```
setTodos(prevTodos => {
// 🚩 Mistake: mutating state
prevTodos.push(createTodo());
});
```
Because React calls your updater function twice, you’ll see the todo was added twice, so you’ll know that there is a mistake. In this example, you can fix the mistake by [replacing the array instead of mutating it]():
```
setTodos(prevTodos => {
// ✅ Correct: replacing with new state
return [...prevTodos, createTodo()];
});
```
Now that this updater function is pure, calling it an extra time doesn’t make a difference in behavior. This is why React calling it twice helps you find mistakes. **Only component, initializer, and updater functions need to be pure.** Event handlers don’t need to be pure, so React will never call your event handlers twice.
Read [keeping components pure](https://react.dev/learn/keeping-components-pure) to learn more.
* * *
### I’m trying to set state to a function, but it gets called instead[Link for I’m trying to set state to a function, but it gets called instead]()
You can’t put a function into state like this:
```
const [fn, setFn] = useState(someFunction);
function handleClick() {
setFn(someOtherFunction);
}
```
Because you’re passing a function, React assumes that `someFunction` is an [initializer function](), and that `someOtherFunction` is an [updater function](), so it tries to call them and store the result. To actually *store* a function, you have to put `() =>` before them in both cases. Then React will store the functions you pass.
```
const [fn, setFn] = useState(() => someFunction);
function handleClick() {
setFn(() => someOtherFunction);
}
```
[PrevioususeRef](https://react.dev/reference/react/useRef)
[NextuseSyncExternalStore](https://react.dev/reference/react/useSyncExternalStore) |
https://react.dev/reference/react/Fragment | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react/components)
# <Fragment> (<>...</>)[Link for this heading]()
`<Fragment>`, often used via `<>...</>` syntax, lets you group elements without a wrapper node.
```
<>
<OneChild />
<AnotherChild />
</>
```
- [Reference]()
- [`<Fragment>`]()
- [Usage]()
- [Returning multiple elements]()
- [Assigning multiple elements to a variable]()
- [Grouping elements with text]()
- [Rendering a list of Fragments]()
* * *
## Reference[Link for Reference]()
### `<Fragment>`[Link for this heading]()
Wrap elements in `<Fragment>` to group them together in situations where you need a single element. Grouping elements in `Fragment` has no effect on the resulting DOM; it is the same as if the elements were not grouped. The empty JSX tag `<></>` is shorthand for `<Fragment></Fragment>` in most cases.
#### Props[Link for Props]()
- **optional** `key`: Fragments declared with the explicit `<Fragment>` syntax may have [keys.](https://react.dev/learn/rendering-lists)
#### Caveats[Link for Caveats]()
- If you want to pass `key` to a Fragment, you can’t use the `<>...</>` syntax. You have to explicitly import `Fragment` from `'react'` and render `<Fragment key={yourKey}>...</Fragment>`.
- React does not [reset state](https://react.dev/learn/preserving-and-resetting-state) when you go from rendering `<><Child /></>` to `[<Child />]` or back, or when you go from rendering `<><Child /></>` to `<Child />` and back. This only works a single level deep: for example, going from `<><><Child /></></>` to `<Child />` resets the state. See the precise semantics [here.](https://gist.github.com/clemmy/b3ef00f9507909429d8aa0d3ee4f986b)
* * *
## Usage[Link for Usage]()
### Returning multiple elements[Link for Returning multiple elements]()
Use `Fragment`, or the equivalent `<>...</>` syntax, to group multiple elements together. You can use it to put multiple elements in any place where a single element can go. For example, a component can only return one element, but by using a Fragment you can group multiple elements together and then return them as a group:
```
function Post() {
return (
<>
<PostTitle />
<PostBody />
</>
);
}
```
Fragments are useful because grouping elements with a Fragment has no effect on layout or styles, unlike if you wrapped the elements in another container like a DOM element. If you inspect this example with the browser tools, you’ll see that all `<h1>` and `<article>` DOM nodes appear as siblings without wrappers around them:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function Blog() {
return (
<>
<Post title="An update" body="It's been a while since I posted..." />
<Post title="My new blog" body="I am starting a new blog!" />
</>
)
}
function Post({ title, body }) {
return (
<>
<PostTitle title={title} />
<PostBody body={body} />
</>
);
}
function PostTitle({ title }) {
return <h1>{title}</h1>
}
function PostBody({ body }) {
return (
<article>
<p>{body}</p>
</article>
);
}
```
Show more
##### Deep Dive
#### How to write a Fragment without the special syntax?[Link for How to write a Fragment without the special syntax?]()
Show Details
The example above is equivalent to importing `Fragment` from React:
```
import { Fragment } from 'react';
function Post() {
return (
<Fragment>
<PostTitle />
<PostBody />
</Fragment>
);
}
```
Usually you won’t need this unless you need to [pass a `key` to your `Fragment`.]()
* * *
### Assigning multiple elements to a variable[Link for Assigning multiple elements to a variable]()
Like any other element, you can assign Fragment elements to variables, pass them as props, and so on:
```
function CloseDialog() {
const buttons = (
<>
<OKButton />
<CancelButton />
</>
);
return (
<AlertDialog buttons={buttons}>
Are you sure you want to leave this page?
</AlertDialog>
);
}
```
* * *
### Grouping elements with text[Link for Grouping elements with text]()
You can use `Fragment` to group text together with components:
```
function DateRangePicker({ start, end }) {
return (
<>
From
<DatePicker date={start} />
to
<DatePicker date={end} />
</>
);
}
```
* * *
### Rendering a list of Fragments[Link for Rendering a list of Fragments]()
Here’s a situation where you need to write `Fragment` explicitly instead of using the `<></>` syntax. When you [render multiple elements in a loop](https://react.dev/learn/rendering-lists), you need to assign a `key` to each element. If the elements within the loop are Fragments, you need to use the normal JSX element syntax in order to provide the `key` attribute:
```
function Blog() {
return posts.map(post =>
<Fragment key={post.id}>
<PostTitle title={post.title} />
<PostBody body={post.body} />
</Fragment>
);
}
```
You can inspect the DOM to verify that there are no wrapper elements around the Fragment children:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Fragment } from 'react';
const posts = [
{ id: 1, title: 'An update', body: "It's been a while since I posted..." },
{ id: 2, title: 'My new blog', body: 'I am starting a new blog!' }
];
export default function Blog() {
return posts.map(post =>
<Fragment key={post.id}>
<PostTitle title={post.title} />
<PostBody body={post.body} />
</Fragment>
);
}
function PostTitle({ title }) {
return <h1>{title}</h1>
}
function PostBody({ body }) {
return (
<article>
<p>{body}</p>
</article>
);
}
```
Show more
[PreviousComponents](https://react.dev/reference/react/components)
[Next<Profiler>](https://react.dev/reference/react/Profiler) |
https://react.dev/reference/react/useSyncExternalStore | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useSyncExternalStore[Link for this heading]()
`useSyncExternalStore` is a React Hook that lets you subscribe to an external store.
```
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)
```
- [Reference]()
- [`useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)`]()
- [Usage]()
- [Subscribing to an external store]()
- [Subscribing to a browser API]()
- [Extracting the logic to a custom Hook]()
- [Adding support for server rendering]()
- [Troubleshooting]()
- [I’m getting an error: “The result of `getSnapshot` should be cached”]()
- [My `subscribe` function gets called after every re-render]()
* * *
## Reference[Link for Reference]()
### `useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)`[Link for this heading]()
Call `useSyncExternalStore` at the top level of your component to read a value from an external data store.
```
import { useSyncExternalStore } from 'react';
import { todosStore } from './todoStore.js';
function TodosApp() {
const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot);
// ...
}
```
It returns the snapshot of the data in the store. You need to pass two functions as arguments:
1. The `subscribe` function should subscribe to the store and return a function that unsubscribes.
2. The `getSnapshot` function should read a snapshot of the data from the store.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `subscribe`: A function that takes a single `callback` argument and subscribes it to the store. When the store changes, it should invoke the provided `callback`, which will cause React to re-call `getSnapshot` and (if needed) re-render the component. The `subscribe` function should return a function that cleans up the subscription.
- `getSnapshot`: A function that returns a snapshot of the data in the store that’s needed by the component. While the store has not changed, repeated calls to `getSnapshot` must return the same value. If the store changes and the returned value is different (as compared by [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), React re-renders the component.
- **optional** `getServerSnapshot`: A function that returns the initial snapshot of the data in the store. It will be used only during server rendering and during hydration of server-rendered content on the client. The server snapshot must be the same between the client and the server, and is usually serialized and passed from the server to the client. If you omit this argument, rendering the component on the server will throw an error.
#### Returns[Link for Returns]()
The current snapshot of the store which you can use in your rendering logic.
#### Caveats[Link for Caveats]()
- The store snapshot returned by `getSnapshot` must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.
- If a different `subscribe` function is passed during a re-render, React will re-subscribe to the store using the newly passed `subscribe` function. You can prevent this by declaring `subscribe` outside the component.
- If the store is mutated during a [non-blocking Transition update](https://react.dev/reference/react/useTransition), React will fall back to performing that update as blocking. Specifically, for every Transition update, React will call `getSnapshot` a second time just before applying changes to the DOM. If it returns a different value than when it was called originally, React will restart the update from scratch, this time applying it as a blocking update, to ensure that every component on screen is reflecting the same version of the store.
- It’s not recommended to *suspend* a render based on a store value returned by `useSyncExternalStore`. The reason is that mutations to the external store cannot be marked as [non-blocking Transition updates](https://react.dev/reference/react/useTransition), so they will trigger the nearest [`Suspense` fallback](https://react.dev/reference/react/Suspense), replacing already-rendered content on screen with a loading spinner, which typically makes a poor UX.
For example, the following are discouraged:
```
const LazyProductDetailPage = lazy(() => import('./ProductDetailPage.js'));
function ShoppingApp() {
const selectedProductId = useSyncExternalStore(...);
// ❌ Calling `use` with a Promise dependent on `selectedProductId`
const data = use(fetchItem(selectedProductId))
// ❌ Conditionally rendering a lazy component based on `selectedProductId`
return selectedProductId != null ? <LazyProductDetailPage /> : <FeaturedProducts />;
}
```
* * *
## Usage[Link for Usage]()
### Subscribing to an external store[Link for Subscribing to an external store]()
Most of your React components will only read data from their [props,](https://react.dev/learn/passing-props-to-a-component) [state,](https://react.dev/reference/react/useState) and [context.](https://react.dev/reference/react/useContext) However, sometimes a component needs to read some data from some store outside of React that changes over time. This includes:
- Third-party state management libraries that hold state outside of React.
- Browser APIs that expose a mutable value and events to subscribe to its changes.
Call `useSyncExternalStore` at the top level of your component to read a value from an external data store.
```
import { useSyncExternalStore } from 'react';
import { todosStore } from './todoStore.js';
function TodosApp() {
const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot);
// ...
}
```
It returns the snapshot of the data in the store. You need to pass two functions as arguments:
1. The `subscribe` function should subscribe to the store and return a function that unsubscribes.
2. The `getSnapshot` function should read a snapshot of the data from the store.
React will use these functions to keep your component subscribed to the store and re-render it on changes.
For example, in the sandbox below, `todosStore` is implemented as an external store that stores data outside of React. The `TodosApp` component connects to that external store with the `useSyncExternalStore` Hook.
App.jstodoStore.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useSyncExternalStore } from 'react';
import { todosStore } from './todoStore.js';
export default function TodosApp() {
const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot);
return (
<>
<button onClick={() => todosStore.addTodo()}>Add todo</button>
<hr />
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</>
);
}
```
Show more
### Note
When possible, we recommend using built-in React state with [`useState`](https://react.dev/reference/react/useState) and [`useReducer`](https://react.dev/reference/react/useReducer) instead. The `useSyncExternalStore` API is mostly useful if you need to integrate with existing non-React code.
* * *
### Subscribing to a browser API[Link for Subscribing to a browser API]()
Another reason to add `useSyncExternalStore` is when you want to subscribe to some value exposed by the browser that changes over time. For example, suppose that you want your component to display whether the network connection is active. The browser exposes this information via a property called [`navigator.onLine`.](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine)
This value can change without React’s knowledge, so you should read it with `useSyncExternalStore`.
```
import { useSyncExternalStore } from 'react';
function ChatIndicator() {
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
// ...
}
```
To implement the `getSnapshot` function, read the current value from the browser API:
```
function getSnapshot() {
return navigator.onLine;
}
```
Next, you need to implement the `subscribe` function. For example, when `navigator.onLine` changes, the browser fires the [`online`](https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event) and [`offline`](https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event) events on the `window` object. You need to subscribe the `callback` argument to the corresponding events, and then return a function that cleans up the subscriptions:
```
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
```
Now React knows how to read the value from the external `navigator.onLine` API and how to subscribe to its changes. Disconnect your device from the network and notice that the component re-renders in response:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useSyncExternalStore } from 'react';
export default function ChatIndicator() {
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
return <h1>{isOnline ? '✅ Online' : '❌ Disconnected'}</h1>;
}
function getSnapshot() {
return navigator.onLine;
}
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
```
Show more
* * *
### Extracting the logic to a custom Hook[Link for Extracting the logic to a custom Hook]()
Usually you won’t write `useSyncExternalStore` directly in your components. Instead, you’ll typically call it from your own custom Hook. This lets you use the same external store from different components.
For example, this custom `useOnlineStatus` Hook tracks whether the network is online:
```
import { useSyncExternalStore } from 'react';
export function useOnlineStatus() {
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
return isOnline;
}
function getSnapshot() {
// ...
}
function subscribe(callback) {
// ...
}
```
Now different components can call `useOnlineStatus` without repeating the underlying implementation:
App.jsuseOnlineStatus.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useOnlineStatus } from './useOnlineStatus.js';
function StatusBar() {
const isOnline = useOnlineStatus();
return <h1>{isOnline ? '✅ Online' : '❌ Disconnected'}</h1>;
}
function SaveButton() {
const isOnline = useOnlineStatus();
function handleSaveClick() {
console.log('✅ Progress saved');
}
return (
<button disabled={!isOnline} onClick={handleSaveClick}>
{isOnline ? 'Save progress' : 'Reconnecting...'}
</button>
);
}
export default function App() {
return (
<>
<SaveButton />
<StatusBar />
</>
);
}
```
Show more
* * *
### Adding support for server rendering[Link for Adding support for server rendering]()
If your React app uses [server rendering,](https://react.dev/reference/react-dom/server) your React components will also run outside the browser environment to generate the initial HTML. This creates a few challenges when connecting to an external store:
- If you’re connecting to a browser-only API, it won’t work because it does not exist on the server.
- If you’re connecting to a third-party data store, you’ll need its data to match between the server and client.
To solve these issues, pass a `getServerSnapshot` function as the third argument to `useSyncExternalStore`:
```
import { useSyncExternalStore } from 'react';
export function useOnlineStatus() {
const isOnline = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
return isOnline;
}
function getSnapshot() {
return navigator.onLine;
}
function getServerSnapshot() {
return true; // Always show "Online" for server-generated HTML
}
function subscribe(callback) {
// ...
}
```
The `getServerSnapshot` function is similar to `getSnapshot`, but it runs only in two situations:
- It runs on the server when generating the HTML.
- It runs on the client during [hydration](https://react.dev/reference/react-dom/client/hydrateRoot), i.e. when React takes the server HTML and makes it interactive.
This lets you provide the initial snapshot value which will be used before the app becomes interactive. If there is no meaningful initial value for the server rendering, omit this argument to [force rendering on the client.](https://react.dev/reference/react/Suspense)
### Note
Make sure that `getServerSnapshot` returns the same exact data on the initial client render as it returned on the server. For example, if `getServerSnapshot` returned some prepopulated store content on the server, you need to transfer this content to the client. One way to do this is to emit a `<script>` tag during server rendering that sets a global like `window.MY_STORE_DATA`, and read from that global on the client in `getServerSnapshot`. Your external store should provide instructions on how to do that.
* * *
## Troubleshooting[Link for Troubleshooting]()
### I’m getting an error: “The result of `getSnapshot` should be cached”[Link for this heading]()
This error means your `getSnapshot` function returns a new object every time it’s called, for example:
```
function getSnapshot() {
// 🔴 Do not return always different objects from getSnapshot
return {
todos: myStore.todos
};
}
```
React will re-render the component if `getSnapshot` return value is different from the last time. This is why, if you always return a different value, you will enter an infinite loop and get this error.
Your `getSnapshot` object should only return a different object if something has actually changed. If your store contains immutable data, you can return that data directly:
```
function getSnapshot() {
// ✅ You can return immutable data
return myStore.todos;
}
```
If your store data is mutable, your `getSnapshot` function should return an immutable snapshot of it. This means it *does* need to create new objects, but it shouldn’t do this for every single call. Instead, it should store the last calculated snapshot, and return the same snapshot as the last time if the data in the store has not changed. How you determine whether mutable data has changed depends on your mutable store.
* * *
### My `subscribe` function gets called after every re-render[Link for this heading]()
This `subscribe` function is defined *inside* a component so it is different on every re-render:
```
function ChatIndicator() {
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
// 🚩 Always a different function, so React will resubscribe on every re-render
function subscribe() {
// ...
}
// ...
}
```
React will resubscribe to your store if you pass a different `subscribe` function between re-renders. If this causes performance issues and you’d like to avoid resubscribing, move the `subscribe` function outside:
```
function ChatIndicator() {
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
// ...
}
// ✅ Always the same function, so React won't need to resubscribe
function subscribe() {
// ...
}
```
Alternatively, wrap `subscribe` into [`useCallback`](https://react.dev/reference/react/useCallback) to only resubscribe when some argument changes:
```
function ChatIndicator({ userId }) {
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
// ✅ Same function as long as userId doesn't change
const subscribe = useCallback(() => {
// ...
}, [userId]);
// ...
}
```
[PrevioususeState](https://react.dev/reference/react/useState)
[NextuseTransition](https://react.dev/reference/react/useTransition) |
https://react.dev/reference/react/useInsertionEffect | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useInsertionEffect[Link for this heading]()
### Pitfall
`useInsertionEffect` is for CSS-in-JS library authors. Unless you are working on a CSS-in-JS library and need a place to inject the styles, you probably want [`useEffect`](https://react.dev/reference/react/useEffect) or [`useLayoutEffect`](https://react.dev/reference/react/useLayoutEffect) instead.
`useInsertionEffect` allows inserting elements into the DOM before any layout Effects fire.
```
useInsertionEffect(setup, dependencies?)
```
- [Reference]()
- [`useInsertionEffect(setup, dependencies?)`]()
- [Usage]()
- [Injecting dynamic styles from CSS-in-JS libraries]()
* * *
## Reference[Link for Reference]()
### `useInsertionEffect(setup, dependencies?)`[Link for this heading]()
Call `useInsertionEffect` to insert styles before any Effects fire that may need to read layout:
```
import { useInsertionEffect } from 'react';
// Inside your CSS-in-JS library
function useCSS(rule) {
useInsertionEffect(() => {
// ... inject <style> tags here ...
});
return rule;
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `setup`: The function with your Effect’s logic. Your setup function may also optionally return a *cleanup* function. When your component is added to the DOM, but before any layout Effects fire, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. When your component is removed from the DOM, React will run your cleanup function.
- **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](https://react.dev/learn/editor-setup), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don’t specify the dependencies at all, your Effect will re-run after every re-render of the component.
#### Returns[Link for Returns]()
`useInsertionEffect` returns `undefined`.
#### Caveats[Link for Caveats]()
- Effects only run on the client. They don’t run during server rendering.
- You can’t update state from inside `useInsertionEffect`.
- By the time `useInsertionEffect` runs, refs are not attached yet.
- `useInsertionEffect` may run either before or after the DOM has been updated. You shouldn’t rely on the DOM being updated at any particular time.
- Unlike other types of Effects, which fire cleanup for every Effect and then setup for every Effect, `useInsertionEffect` will fire both cleanup and setup one component at a time. This results in an “interleaving” of the cleanup and setup functions.
* * *
## Usage[Link for Usage]()
### Injecting dynamic styles from CSS-in-JS libraries[Link for Injecting dynamic styles from CSS-in-JS libraries]()
Traditionally, you would style React components using plain CSS.
```
// In your JS file:
<button className="success" />
// In your CSS file:
.success { color: green; }
```
Some teams prefer to author styles directly in JavaScript code instead of writing CSS files. This usually requires using a CSS-in-JS library or a tool. There are three common approaches to CSS-in-JS:
1. Static extraction to CSS files with a compiler
2. Inline styles, e.g. `<div style={{ opacity: 1 }}>`
3. Runtime injection of `<style>` tags
If you use CSS-in-JS, we recommend a combination of the first two approaches (CSS files for static styles, inline styles for dynamic styles). **We don’t recommend runtime `<style>` tag injection for two reasons:**
1. Runtime injection forces the browser to recalculate the styles a lot more often.
2. Runtime injection can be very slow if it happens at the wrong time in the React lifecycle.
The first problem is not solvable, but `useInsertionEffect` helps you solve the second problem.
Call `useInsertionEffect` to insert the styles before any layout Effects fire:
```
// Inside your CSS-in-JS library
let isInserted = new Set();
function useCSS(rule) {
useInsertionEffect(() => {
// As explained earlier, we don't recommend runtime injection of <style> tags.
// But if you have to do it, then it's important to do in useInsertionEffect.
if (!isInserted.has(rule)) {
isInserted.add(rule);
document.head.appendChild(getStyleForRule(rule));
}
});
return rule;
}
function Button() {
const className = useCSS('...');
return <div className={className} />;
}
```
Similarly to `useEffect`, `useInsertionEffect` does not run on the server. If you need to collect which CSS rules have been used on the server, you can do it during rendering:
```
let collectedRulesSet = new Set();
function useCSS(rule) {
if (typeof window === 'undefined') {
collectedRulesSet.add(rule);
}
useInsertionEffect(() => {
// ...
});
return rule;
}
```
[Read more about upgrading CSS-in-JS libraries with runtime injection to `useInsertionEffect`.](https://github.com/reactwg/react-18/discussions/110)
##### Deep Dive
#### How is this better than injecting styles during rendering or useLayoutEffect?[Link for How is this better than injecting styles during rendering or useLayoutEffect?]()
Show Details
If you insert styles during rendering and React is processing a [non-blocking update,](https://react.dev/reference/react/useTransition) the browser will recalculate the styles every single frame while rendering a component tree, which can be **extremely slow.**
`useInsertionEffect` is better than inserting styles during [`useLayoutEffect`](https://react.dev/reference/react/useLayoutEffect) or [`useEffect`](https://react.dev/reference/react/useEffect) because it ensures that by the time other Effects run in your components, the `<style>` tags have already been inserted. Otherwise, layout calculations in regular Effects would be wrong due to outdated styles.
[PrevioususeImperativeHandle](https://react.dev/reference/react/useImperativeHandle)
[NextuseLayoutEffect](https://react.dev/reference/react/useLayoutEffect) |
https://react.dev/reference/react/StrictMode | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react/components)
# <StrictMode>[Link for this heading]()
`<StrictMode>` lets you find common bugs in your components early during development.
```
<StrictMode>
<App />
</StrictMode>
```
- [Reference]()
- [`<StrictMode>`]()
- [Usage]()
- [Enabling Strict Mode for entire app]()
- [Enabling Strict Mode for a part of the app]()
- [Fixing bugs found by double rendering in development]()
- [Fixing bugs found by re-running Effects in development]()
- [Fixing bugs found by re-running ref callbacks in development]()
- [Fixing deprecation warnings enabled by Strict Mode]()
* * *
## Reference[Link for Reference]()
### `<StrictMode>`[Link for this heading]()
Use `StrictMode` to enable additional development behaviors and warnings for the component tree inside:
```
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(
<StrictMode>
<App />
</StrictMode>
);
```
[See more examples below.]()
Strict Mode enables the following development-only behaviors:
- Your components will [re-render an extra time]() to find bugs caused by impure rendering.
- Your components will [re-run Effects an extra time]() to find bugs caused by missing Effect cleanup.
- Your components will [re-run refs callbacks an extra time]() to find bugs caused by missing ref cleanup.
- Your components will [be checked for usage of deprecated APIs.]()
#### Props[Link for Props]()
`StrictMode` accepts no props.
#### Caveats[Link for Caveats]()
- There is no way to opt out of Strict Mode inside a tree wrapped in `<StrictMode>`. This gives you confidence that all components inside `<StrictMode>` are checked. If two teams working on a product disagree whether they find the checks valuable, they need to either reach consensus or move `<StrictMode>` down in the tree.
* * *
## Usage[Link for Usage]()
### Enabling Strict Mode for entire app[Link for Enabling Strict Mode for entire app]()
Strict Mode enables extra development-only checks for the entire component tree inside the `<StrictMode>` component. These checks help you find common bugs in your components early in the development process.
To enable Strict Mode for your entire app, wrap your root component with `<StrictMode>` when you render it:
```
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(
<StrictMode>
<App />
</StrictMode>
);
```
We recommend wrapping your entire app in Strict Mode, especially for newly created apps. If you use a framework that calls [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) for you, check its documentation for how to enable Strict Mode.
Although the Strict Mode checks **only run in development,** they help you find bugs that already exist in your code but can be tricky to reliably reproduce in production. Strict Mode lets you fix bugs before your users report them.
### Note
Strict Mode enables the following checks in development:
- Your components will [re-render an extra time]() to find bugs caused by impure rendering.
- Your components will [re-run Effects an extra time]() to find bugs caused by missing Effect cleanup.
- Your components will [re-run ref callbacks an extra time]() to find bugs caused by missing ref cleanup.
- Your components will [be checked for usage of deprecated APIs.]()
**All of these checks are development-only and do not impact the production build.**
* * *
### Enabling Strict Mode for a part of the app[Link for Enabling Strict Mode for a part of the app]()
You can also enable Strict Mode for any part of your application:
```
import { StrictMode } from 'react';
function App() {
return (
<>
<Header />
<StrictMode>
<main>
<Sidebar />
<Content />
</main>
</StrictMode>
<Footer />
</>
);
}
```
In this example, Strict Mode checks will not run against the `Header` and `Footer` components. However, they will run on `Sidebar` and `Content`, as well as all of the components inside them, no matter how deep.
* * *
### Fixing bugs found by double rendering in development[Link for Fixing bugs found by double rendering in development]()
[React assumes that every component you write is a pure function.](https://react.dev/learn/keeping-components-pure) This means that React components you write must always return the same JSX given the same inputs (props, state, and context).
Components breaking this rule behave unpredictably and cause bugs. To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) **twice in development.** This includes:
- Your component function body (only top-level logic, so this doesn’t include code inside event handlers)
- Functions that you pass to [`useState`](https://react.dev/reference/react/useState), [`set` functions](https://react.dev/reference/react/useState), [`useMemo`](https://react.dev/reference/react/useMemo), or [`useReducer`](https://react.dev/reference/react/useReducer)
- Some class component methods like [`constructor`](https://react.dev/reference/react/Component), [`render`](https://react.dev/reference/react/Component), [`shouldComponentUpdate`](https://react.dev/reference/react/Component) ([see the whole list](https://reactjs.org/docs/strict-mode.html))
If a function is pure, running it twice does not change its behavior because a pure function produces the same result every time. However, if a function is impure (for example, it mutates the data it receives), running it twice tends to be noticeable (that’s what makes it impure!) This helps you spot and fix the bug early.
**Here is an example to illustrate how double rendering in Strict Mode helps you find bugs early.**
This `StoryTray` component takes an array of `stories` and adds one last “Create Story” item at the end:
index.jsApp.jsStoryTray.js
StoryTray.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function StoryTray({ stories }) {
const items = stories;
items.push({ id: 'create', label: 'Create Story' });
return (
<ul>
{items.map(story => (
<li key={story.id}>
{story.label}
</li>
))}
</ul>
);
}
```
There is a mistake in the code above. However, it is easy to miss because the initial output appears correct.
This mistake will become more noticeable if the `StoryTray` component re-renders multiple times. For example, let’s make the `StoryTray` re-render with a different background color whenever you hover over it:
index.jsApp.jsStoryTray.js
StoryTray.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function StoryTray({ stories }) {
const [isHover, setIsHover] = useState(false);
const items = stories;
items.push({ id: 'create', label: 'Create Story' });
return (
<ul
onPointerEnter={() => setIsHover(true)}
onPointerLeave={() => setIsHover(false)}
style={{
backgroundColor: isHover ? '#ddd' : '#fff'
}}
>
{items.map(story => (
<li key={story.id}>
{story.label}
</li>
))}
</ul>
);
}
```
Show more
Notice how every time you hover over the `StoryTray` component, “Create Story” gets added to the list again. The intention of the code was to add it once at the end. But `StoryTray` directly modifies the `stories` array from the props. Every time `StoryTray` renders, it adds “Create Story” again at the end of the same array. In other words, `StoryTray` is not a pure function—running it multiple times produces different results.
To fix this problem, you can make a copy of the array, and modify that copy instead of the original one:
```
export default function StoryTray({ stories }) {
const items = stories.slice(); // Clone the array
// ✅ Good: Pushing into a new array
items.push({ id: 'create', label: 'Create Story' });
```
This would [make the `StoryTray` function pure.](https://react.dev/learn/keeping-components-pure) Each time it is called, it would only modify a new copy of the array, and would not affect any external objects or variables. This solves the bug, but you had to make the component re-render more often before it became obvious that something is wrong with its behavior.
**In the original example, the bug wasn’t obvious. Now let’s wrap the original (buggy) code in `<StrictMode>`:**
index.jsApp.jsStoryTray.js
StoryTray.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function StoryTray({ stories }) {
const items = stories;
items.push({ id: 'create', label: 'Create Story' });
return (
<ul>
{items.map(story => (
<li key={story.id}>
{story.label}
</li>
))}
</ul>
);
}
```
**Strict Mode *always* calls your rendering function twice, so you can see the mistake right away** (“Create Story” appears twice). This lets you notice such mistakes early in the process. When you fix your component to render in Strict Mode, you *also* fix many possible future production bugs like the hover functionality from before:
index.jsApp.jsStoryTray.js
StoryTray.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function StoryTray({ stories }) {
const [isHover, setIsHover] = useState(false);
const items = stories.slice(); // Clone the array
items.push({ id: 'create', label: 'Create Story' });
return (
<ul
onPointerEnter={() => setIsHover(true)}
onPointerLeave={() => setIsHover(false)}
style={{
backgroundColor: isHover ? '#ddd' : '#fff'
}}
>
{items.map(story => (
<li key={story.id}>
{story.label}
</li>
))}
</ul>
);
}
```
Show more
Without Strict Mode, it was easy to miss the bug until you added more re-renders. Strict Mode made the same bug appear right away. Strict Mode helps you find bugs before you push them to your team and to your users.
[Read more about keeping components pure.](https://react.dev/learn/keeping-components-pure)
### Note
If you have [React DevTools](https://react.dev/learn/react-developer-tools) installed, any `console.log` calls during the second render call will appear slightly dimmed. React DevTools also offers a setting (off by default) to suppress them completely.
* * *
### Fixing bugs found by re-running Effects in development[Link for Fixing bugs found by re-running Effects in development]()
Strict Mode can also help find bugs in [Effects.](https://react.dev/learn/synchronizing-with-effects)
Every Effect has some setup code and may have some cleanup code. Normally, React calls setup when the component *mounts* (is added to the screen) and calls cleanup when the component *unmounts* (is removed from the screen). React then calls cleanup and setup again if its dependencies changed since the last render.
When Strict Mode is on, React will also run **one extra setup+cleanup cycle in development for every Effect.** This may feel surprising, but it helps reveal subtle bugs that are hard to catch manually.
**Here is an example to illustrate how re-running Effects in Strict Mode helps you find bugs early.**
Consider this example that connects a component to a chat:
index.jsApp.jschat.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from 'react-dom/client';
import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root"));
root.render(<App />);
```
There is an issue with this code, but it might not be immediately clear.
To make the issue more obvious, let’s implement a feature. In the example below, `roomId` is not hardcoded. Instead, the user can select the `roomId` that they want to connect to from a dropdown. Click “Open chat” and then select different chat rooms one by one. Keep track of the number of active connections in the console:
index.jsApp.jschat.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from 'react-dom/client';
import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root"));
root.render(<App />);
```
You’ll notice that the number of open connections always keeps growing. In a real app, this would cause performance and network problems. The issue is that [your Effect is missing a cleanup function:](https://react.dev/learn/synchronizing-with-effects)
```
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
```
Now that your Effect “cleans up” after itself and destroys the outdated connections, the leak is solved. However, notice that the problem did not become visible until you’ve added more features (the select box).
**In the original example, the bug wasn’t obvious. Now let’s wrap the original (buggy) code in `<StrictMode>`:**
index.jsApp.jschat.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<App />
</StrictMode>
);
```
**With Strict Mode, you immediately see that there is a problem** (the number of active connections jumps to 2). Strict Mode runs an extra setup+cleanup cycle for every Effect. This Effect has no cleanup logic, so it creates an extra connection but doesn’t destroy it. This is a hint that you’re missing a cleanup function.
Strict Mode lets you notice such mistakes early in the process. When you fix your Effect by adding a cleanup function in Strict Mode, you *also* fix many possible future production bugs like the select box from before:
index.jsApp.jschat.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<App />
</StrictMode>
);
```
Notice how the active connection count in the console doesn’t keep growing anymore.
Without Strict Mode, it was easy to miss that your Effect needed cleanup. By running *setup → cleanup → setup* instead of *setup* for your Effect in development, Strict Mode made the missing cleanup logic more noticeable.
[Read more about implementing Effect cleanup.](https://react.dev/learn/synchronizing-with-effects)
* * *
### Fixing bugs found by re-running ref callbacks in development[Link for Fixing bugs found by re-running ref callbacks in development]()
Strict Mode can also help find bugs in [callbacks refs.](https://react.dev/learn/manipulating-the-dom-with-refs)
Every callback `ref` has some setup code and may have some cleanup code. Normally, React calls setup when the element is *created* (is added to the DOM) and calls cleanup when the element is *removed* (is removed from the DOM).
When Strict Mode is on, React will also run **one extra setup+cleanup cycle in development for every callback `ref`.** This may feel surprising, but it helps reveal subtle bugs that are hard to catch manually.
Consider this example, which allows you to select an animal and then scroll to one of them. Notice when you switch from “Cats” to “Dogs”, the console logs show that the number of animals in the list keeps growing, and the “Scroll to” buttons stop working:
index.jsApp.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef, useState } from "react";
export default function AnimalFriends() {
const itemsRef = useRef([]);
const [animalList, setAnimalList] = useState(setupAnimalList);
const [animal, setAnimal] = useState('cat');
function scrollToAnimal(index) {
const list = itemsRef.current;
const {node} = list[index];
node.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "center",
});
}
const animals = animalList.filter(a => a.type === animal)
return (
<>
<nav>
<button onClick={() => setAnimal('cat')}>Cats</button>
<button onClick={() => setAnimal('dog')}>Dogs</button>
</nav>
<hr />
<nav>
<span>Scroll to:</span>{animals.map((animal, index) => (
<button key={animal.src} onClick={() => scrollToAnimal(index)}>
{index}
</button>
))}
</nav>
<div>
<ul>
{animals.map((animal) => (
<li
key={animal.src}
ref={(node) => {
const list = itemsRef.current;
const item = {animal: animal, node};
list.push(item);
console.log(`✅ Adding animal to the map. Total animals: ${list.length}`);
if (list.length > 10) {
console.log('❌ Too many animals in the list!');
}
return () => {
// 🚩 No cleanup, this is a bug!
}
}}
>
<img src={animal.src} />
</li>
))}
</ul>
</div>
</>
);
}
function setupAnimalList() {
const animalList = [];
for (let i = 0; i < 10; i++) {
animalList.push({type: 'cat', src: "https://loremflickr.com/320/240/cat?lock=" + i});
}
for (let i = 0; i < 10; i++) {
animalList.push({type: 'dog', src: "https://loremflickr.com/320/240/dog?lock=" + i});
}
return animalList;
}
```
Show more
**This is a production bug!** Since the ref callback doesn’t remove animals from the list in the cleanup, the list of animals keeps growing. This is a memory leak that can cause performance problems in a real app, and breaks the behavior of the app.
The issue is the ref callback doesn’t cleanup after itself:
```
<li
ref={node => {
const list = itemsRef.current;
const item = {animal, node};
list.push(item);
return () => {
// 🚩 No cleanup, this is a bug!
}
}}
</li>
```
Now let’s wrap the original (buggy) code in `<StrictMode>`:
index.jsApp.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef, useState } from "react";
export default function AnimalFriends() {
const itemsRef = useRef([]);
const [animalList, setAnimalList] = useState(setupAnimalList);
const [animal, setAnimal] = useState('cat');
function scrollToAnimal(index) {
const list = itemsRef.current;
const {node} = list[index];
node.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "center",
});
}
const animals = animalList.filter(a => a.type === animal)
return (
<>
<nav>
<button onClick={() => setAnimal('cat')}>Cats</button>
<button onClick={() => setAnimal('dog')}>Dogs</button>
</nav>
<hr />
<nav>
<span>Scroll to:</span>{animals.map((animal, index) => (
<button key={animal.src} onClick={() => scrollToAnimal(index)}>
{index}
</button>
))}
</nav>
<div>
<ul>
{animals.map((animal) => (
<li
key={animal.src}
ref={(node) => {
const list = itemsRef.current;
const item = {animal: animal, node}
list.push(item);
console.log(`✅ Adding animal to the map. Total animals: ${list.length}`);
if (list.length > 10) {
console.log('❌ Too many animals in the list!');
}
return () => {
// 🚩 No cleanup, this is a bug!
}
}}
>
<img src={animal.src} />
</li>
))}
</ul>
</div>
</>
);
}
function setupAnimalList() {
const animalList = [];
for (let i = 0; i < 10; i++) {
animalList.push({type: 'cat', src: "https://loremflickr.com/320/240/cat?lock=" + i});
}
for (let i = 0; i < 10; i++) {
animalList.push({type: 'dog', src: "https://loremflickr.com/320/240/dog?lock=" + i});
}
return animalList;
}
```
Show more
**With Strict Mode, you immediately see that there is a problem**. Strict Mode runs an extra setup+cleanup cycle for every callback ref. This callback ref has no cleanup logic, so it adds refs but doesn’t remove them. This is a hint that you’re missing a cleanup function.
Strict Mode lets you eagerly find mistakes in callback refs. When you fix your callback by adding a cleanup function in Strict Mode, you *also* fix many possible future production bugs like the “Scroll to” bug from before:
index.jsApp.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef, useState } from "react";
export default function AnimalFriends() {
const itemsRef = useRef([]);
const [animalList, setAnimalList] = useState(setupAnimalList);
const [animal, setAnimal] = useState('cat');
function scrollToAnimal(index) {
const list = itemsRef.current;
const {node} = list[index];
node.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "center",
});
}
const animals = animalList.filter(a => a.type === animal)
return (
<>
<nav>
<button onClick={() => setAnimal('cat')}>Cats</button>
<button onClick={() => setAnimal('dog')}>Dogs</button>
</nav>
<hr />
<nav>
<span>Scroll to:</span>{animals.map((animal, index) => (
<button key={animal.src} onClick={() => scrollToAnimal(index)}>
{index}
</button>
))}
</nav>
<div>
<ul>
{animals.map((animal) => (
<li
key={animal.src}
ref={(node) => {
const list = itemsRef.current;
const item = {animal, node};
list.push({animal: animal, node});
console.log(`✅ Adding animal to the map. Total animals: ${list.length}`);
if (list.length > 10) {
console.log('❌ Too many animals in the list!');
}
return () => {
list.splice(list.indexOf(item));
console.log(`❌ Removing animal from the map. Total animals: ${itemsRef.current.length}`);
}
}}
>
<img src={animal.src} />
</li>
))}
</ul>
</div>
</>
);
}
function setupAnimalList() {
const animalList = [];
for (let i = 0; i < 10; i++) {
animalList.push({type: 'cat', src: "https://loremflickr.com/320/240/cat?lock=" + i});
}
for (let i = 0; i < 10; i++) {
animalList.push({type: 'dog', src: "https://loremflickr.com/320/240/dog?lock=" + i});
}
return animalList;
}
```
Show more
Now on inital mount in StrictMode, the ref callbacks are all setup, cleaned up, and setup again:
```
...
✅ Adding animal to the map. Total animals: 10
...
❌ Removing animal from the map. Total animals: 0
...
✅ Adding animal to the map. Total animals: 10
```
**This is expected.** Strict Mode confirms that the ref callbacks are cleaned up correctly, so the size never grows above the expected amount. After the fix, there are no memory leaks, and all the features work as expected.
Without Strict Mode, it was easy to miss the bug until you clicked around to app to notice broken features. Strict Mode made the bugs appear right away, before you push them to production.
* * *
### Fixing deprecation warnings enabled by Strict Mode[Link for Fixing deprecation warnings enabled by Strict Mode]()
React warns if some component anywhere inside a `<StrictMode>` tree uses one of these deprecated APIs:
- `UNSAFE_` class lifecycle methods like [`UNSAFE_componentWillMount`](https://react.dev/reference/react/Component). [See alternatives.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html)
These APIs are primarily used in older [class components](https://react.dev/reference/react/Component) so they rarely appear in modern apps.
[Previous<Profiler>](https://react.dev/reference/react/Profiler)
[Next<Suspense>](https://react.dev/reference/react/Suspense) |
https://react.dev/reference/react/Profiler | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react/components)
# <Profiler>[Link for this heading]()
`<Profiler>` lets you measure rendering performance of a React tree programmatically.
```
<Profiler id="App" onRender={onRender}>
<App />
</Profiler>
```
- [Reference]()
- [`<Profiler>`]()
- [`onRender` callback]()
- [Usage]()
- [Measuring rendering performance programmatically]()
- [Measuring different parts of the application]()
* * *
## Reference[Link for Reference]()
### `<Profiler>`[Link for this heading]()
Wrap a component tree in a `<Profiler>` to measure its rendering performance.
```
<Profiler id="App" onRender={onRender}>
<App />
</Profiler>
```
#### Props[Link for Props]()
- `id`: A string identifying the part of the UI you are measuring.
- `onRender`: An [`onRender` callback]() that React calls every time components within the profiled tree update. It receives information about what was rendered and how much time it took.
#### Caveats[Link for Caveats]()
- Profiling adds some additional overhead, so **it is disabled in the production build by default.** To opt into production profiling, you need to enable a [special production build with profiling enabled.](https://fb.me/react-profiling)
* * *
### `onRender` callback[Link for this heading]()
React will call your `onRender` callback with information about what was rendered.
```
function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime) {
// Aggregate or log render timings...
}
```
#### Parameters[Link for Parameters]()
- `id`: The string `id` prop of the `<Profiler>` tree that has just committed. This lets you identify which part of the tree was committed if you are using multiple profilers.
- `phase`: `"mount"`, `"update"` or `"nested-update"`. This lets you know whether the tree has just been mounted for the first time or re-rendered due to a change in props, state, or Hooks.
- `actualDuration`: The number of milliseconds spent rendering the `<Profiler>` and its descendants for the current update. This indicates how well the subtree makes use of memoization (e.g. [`memo`](https://react.dev/reference/react/memo) and [`useMemo`](https://react.dev/reference/react/useMemo)). Ideally this value should decrease significantly after the initial mount as many of the descendants will only need to re-render if their specific props change.
- `baseDuration`: The number of milliseconds estimating how much time it would take to re-render the entire `<Profiler>` subtree without any optimizations. It is calculated by summing up the most recent render durations of each component in the tree. This value estimates a worst-case cost of rendering (e.g. the initial mount or a tree with no memoization). Compare `actualDuration` against it to see if memoization is working.
- `startTime`: A numeric timestamp for when React began rendering the current update.
- `commitTime`: A numeric timestamp for when React committed the current update. This value is shared between all profilers in a commit, enabling them to be grouped if desirable.
* * *
## Usage[Link for Usage]()
### Measuring rendering performance programmatically[Link for Measuring rendering performance programmatically]()
Wrap the `<Profiler>` component around a React tree to measure its rendering performance.
```
<App>
<Profiler id="Sidebar" onRender={onRender}>
<Sidebar />
</Profiler>
<PageContent />
</App>
```
It requires two props: an `id` (string) and an `onRender` callback (function) which React calls any time a component within the tree “commits” an update.
### Pitfall
Profiling adds some additional overhead, so **it is disabled in the production build by default.** To opt into production profiling, you need to enable a [special production build with profiling enabled.](https://fb.me/react-profiling)
### Note
`<Profiler>` lets you gather measurements programmatically. If you’re looking for an interactive profiler, try the Profiler tab in [React Developer Tools](https://react.dev/learn/react-developer-tools). It exposes similar functionality as a browser extension.
* * *
### Measuring different parts of the application[Link for Measuring different parts of the application]()
You can use multiple `<Profiler>` components to measure different parts of your application:
```
<App>
<Profiler id="Sidebar" onRender={onRender}>
<Sidebar />
</Profiler>
<Profiler id="Content" onRender={onRender}>
<Content />
</Profiler>
</App>
```
You can also nest `<Profiler>` components:
```
<App>
<Profiler id="Sidebar" onRender={onRender}>
<Sidebar />
</Profiler>
<Profiler id="Content" onRender={onRender}>
<Content>
<Profiler id="Editor" onRender={onRender}>
<Editor />
</Profiler>
<Preview />
</Content>
</Profiler>
</App>
```
Although `<Profiler>` is a lightweight component, it should be used only when necessary. Each use adds some CPU and memory overhead to an application.
* * *
[Previous<Fragment> (<>)](https://react.dev/reference/react/Fragment)
[Next<StrictMode>](https://react.dev/reference/react/StrictMode) |
https://react.dev/reference/react/useTransition | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useTransition[Link for this heading]()
`useTransition` is a React Hook that lets you render a part of the UI in the background.
```
const [isPending, startTransition] = useTransition()
```
- [Reference]()
- [`useTransition()`]()
- [`startTransition(action)`]()
- [Usage]()
- [Perform non-blocking updates with Actions]()
- [Exposing `action` prop from components]()
- [Displaying a pending visual state]()
- [Preventing unwanted loading indicators]()
- [Building a Suspense-enabled router]()
- [Displaying an error to users with an error boundary]()
- [Troubleshooting]()
- [Updating an input in a Transition doesn’t work]()
- [React doesn’t treat my state update as a Transition]()
- [React doesn’t treat my state update after `await` as a Transition]()
- [I want to call `useTransition` from outside a component]()
- [The function I pass to `startTransition` executes immediately]()
- [My state updates in Transitions are out of order]()
* * *
## Reference[Link for Reference]()
### `useTransition()`[Link for this heading]()
Call `useTransition` at the top level of your component to mark some state updates as Transitions.
```
import { useTransition } from 'react';
function TabContainer() {
const [isPending, startTransition] = useTransition();
// ...
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
`useTransition` does not take any parameters.
#### Returns[Link for Returns]()
`useTransition` returns an array with exactly two items:
1. The `isPending` flag that tells you whether there is a pending Transition.
2. The [`startTransition` function]() that lets you mark updates as a Transition.
* * *
### `startTransition(action)`[Link for this heading]()
The `startTransition` function returned by `useTransition` lets you mark an update as a Transition.
```
function TabContainer() {
const [isPending, startTransition] = useTransition();
const [tab, setTab] = useState('about');
function selectTab(nextTab) {
startTransition(() => {
setTab(nextTab);
});
}
// ...
}
```
### Note
#### Functions called in `startTransition` are called “Actions”.[Link for this heading]()
The function passed to `startTransition` is called an “Action”. By convention, any callback called inside `startTransition` (such as a callback prop) should be named `action` or include the “Action” suffix:
```
function SubmitButton({ submitAction }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(() => {
submitAction();
});
}}
>
Submit
</button>
);
}
```
#### Parameters[Link for Parameters]()
- `action`: A function that updates some state by calling one or more [`set` functions](https://react.dev/reference/react/useState). React calls `action` immediately with no parameters and marks all state updates scheduled synchronously during the `action` function call as Transitions. Any async calls that are awaited in the `action` will be included in the Transition, but currently require wrapping any `set` functions after the `await` in an additional `startTransition` (see [Troubleshooting]()). State updates marked as Transitions will be [non-blocking]() and [will not display unwanted loading indicators]().
#### Returns[Link for Returns]()
`startTransition` does not return anything.
#### Caveats[Link for Caveats]()
- `useTransition` is a Hook, so it can only be called inside components or custom Hooks. If you need to start a Transition somewhere else (for example, from a data library), call the standalone [`startTransition`](https://react.dev/reference/react/startTransition) instead.
- You can wrap an update into a Transition only if you have access to the `set` function of that state. If you want to start a Transition in response to some prop or a custom Hook value, try [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue) instead.
- The function you pass to `startTransition` is called immediately, marking all state updates that happen while it executes as Transitions. If you try to perform state updates in a `setTimeout`, for example, they won’t be marked as Transitions.
- You must wrap any state updates after any async requests in another `startTransition` to mark them as Transitions. This is a known limitation that we will fix in the future (see [Troubleshooting]()).
- The `startTransition` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](https://react.dev/learn/removing-effect-dependencies)
- A state update marked as a Transition will be interrupted by other state updates. For example, if you update a chart component inside a Transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input update.
- Transition updates can’t be used to control text inputs.
- If there are multiple ongoing Transitions, React currently batches them together. This is a limitation that may be removed in a future release.
## Usage[Link for Usage]()
### Perform non-blocking updates with Actions[Link for Perform non-blocking updates with Actions]()
Call `useTransition` at the top of your component to create Actions, and access the pending state:
```
import {useState, useTransition} from 'react';
function CheckoutForm() {
const [isPending, startTransition] = useTransition();
// ...
}
```
`useTransition` returns an array with exactly two items:
1. The `isPending` flag that tells you whether there is a pending Transition.
2. The `startTransition` function that lets you create an Action.
To start a Transition, pass a function to `startTransition` like this:
```
import {useState, useTransition} from 'react';
import {updateQuantity} from './api';
function CheckoutForm() {
const [isPending, startTransition] = useTransition();
const [quantity, setQuantity] = useState(1);
function onSubmit(newQuantity) {
startTransition(async function () {
const savedQuantity = await updateQuantity(newQuantity);
startTransition(() => {
setQuantity(savedQuantity);
});
});
}
// ...
}
```
The function passed to `startTransition` is called the “Action”. You can update state and (optionally) perform side effects within an Action, and the work will be done in the background without blocking user interactions on the page. A Transition can include multiple Actions, and while a Transition is in progress, your UI stays responsive. For example, if the user clicks a tab but then changes their mind and clicks another tab, the second click will be immediately handled without waiting for the first update to finish.
To give the user feedback about in-progress Transitions, to `isPending` state switches to `true` at the first call to `startTransition`, and stays `true` until all Actions complete and the final state is shown to the user. Transitions ensure side effects in Actions to complete in order to [prevent unwanted loading indicators](), and you can provide immediate feedback while the Transition is in progress with `useOptimistic`.
#### The difference between Actions and regular event handling[Link for The difference between Actions and regular event handling]()
1\. Updating the quantity in an Action 2. Updating the quantity without an Action
#### Example 1 of 2: Updating the quantity in an Action[Link for this heading]()
In this example, the `updateQuantity` function simulates a request to the server to update the item’s quantity in the cart. This function is *artificially slowed down* so that it takes at least a second to complete the request.
Update the quantity multiple times quickly. Notice that the pending “Total” state is shown while any requests are in progress, and the “Total” updates only after the final request is complete. Because the update is in an Action, the “quantity” can continue to be updated while the request is in progress.
App.jsItem.jsTotal.jsapi.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useTransition } from "react";
import { updateQuantity } from "./api";
import Item from "./Item";
import Total from "./Total";
export default function App({}) {
const [quantity, setQuantity] = useState(1);
const [isPending, startTransition] = useTransition();
const updateQuantityAction = async newQuantity => {
// To access the pending state of a transition,
// call startTransition again.
startTransition(async () => {
const savedQuantity = await updateQuantity(newQuantity);
startTransition(() => {
setQuantity(savedQuantity);
});
});
};
return (
<div>
<h1>Checkout</h1>
<Item action={updateQuantityAction}/>
<hr />
<Total quantity={quantity} isPending={isPending} />
</div>
);
}
```
Show more
This is a basic example to demonstrate how Actions work, but this example does not handle requests completing out of order. When updating the quantity multiple times, it’s possible for the previous requests to finish after later requests causing the quantity to update out of order. This is a known limitation that we will fix in the future (see [Troubleshooting]() below).
For common use cases, React provides built-in abstractions such as:
- [`useActionState`](https://react.dev/reference/react/useActionState)
- [`<form>` actions](https://react.dev/reference/react-dom/components/form)
- [Server Functions](https://react.dev/reference/rsc/server-functions)
These solutions handle request ordering for you. When using Transitions to build your own custom hooks or libraries that manage async state transitions, you have greater control over the request ordering, but you must handle it yourself.
Next Example
* * *
### Exposing `action` prop from components[Link for this heading]()
You can expose an `action` prop from a component to allow a parent to call an Action.
For example, this `TabButton` component wraps its `onClick` logic in an `action` prop:
```
export default function TabButton({ action, children, isActive }) {
const [isPending, startTransition] = useTransition();
if (isActive) {
return <b>{children}</b>
}
return (
<button onClick={() => {
startTransition(() => {
action();
});
}}>
{children}
</button>
);
}
```
Because the parent component updates its state inside the `action`, that state update gets marked as a Transition. This means you can click on “Posts” and then immediately click “Contact” and it does not block user interactions:
App.jsTabButton.jsAboutTab.jsPostsTab.jsContactTab.js
TabButton.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useTransition } from 'react';
export default function TabButton({ action, children, isActive }) {
const [isPending, startTransition] = useTransition();
if (isActive) {
return <b>{children}</b>
}
return (
<button onClick={() => {
startTransition(() => {
action();
});
}}>
{children}
</button>
);
}
```
Show more
* * *
### Displaying a pending visual state[Link for Displaying a pending visual state]()
You can use the `isPending` boolean value returned by `useTransition` to indicate to the user that a Transition is in progress. For example, the tab button can have a special “pending” visual state:
```
function TabButton({ action, children, isActive }) {
const [isPending, startTransition] = useTransition();
// ...
if (isPending) {
return <b className="pending">{children}</b>;
}
// ...
```
Notice how clicking “Posts” now feels more responsive because the tab button itself updates right away:
App.jsTabButton.jsAboutTab.jsPostsTab.jsContactTab.js
TabButton.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useTransition } from 'react';
export default function TabButton({ action, children, isActive }) {
const [isPending, startTransition] = useTransition();
if (isActive) {
return <b>{children}</b>
}
if (isPending) {
return <b className="pending">{children}</b>;
}
return (
<button onClick={() => {
startTransition(() => {
action();
});
}}>
{children}
</button>
);
}
```
Show more
* * *
### Preventing unwanted loading indicators[Link for Preventing unwanted loading indicators]()
In this example, the `PostsTab` component fetches some data using [use](https://react.dev/reference/react/use). When you click the “Posts” tab, the `PostsTab` component *suspends*, causing the closest loading fallback to appear:
App.jsTabButton.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState } from 'react';
import TabButton from './TabButton.js';
import AboutTab from './AboutTab.js';
import PostsTab from './PostsTab.js';
import ContactTab from './ContactTab.js';
export default function TabContainer() {
const [tab, setTab] = useState('about');
return (
<Suspense fallback={<h1>🌀 Loading...</h1>}>
<TabButton
isActive={tab === 'about'}
action={() => setTab('about')}
>
About
</TabButton>
<TabButton
isActive={tab === 'posts'}
action={() => setTab('posts')}
>
Posts
</TabButton>
<TabButton
isActive={tab === 'contact'}
action={() => setTab('contact')}
>
Contact
</TabButton>
<hr />
{tab === 'about' && <AboutTab />}
{tab === 'posts' && <PostsTab />}
{tab === 'contact' && <ContactTab />}
</Suspense>
);
}
```
Show more
Hiding the entire tab container to show a loading indicator leads to a jarring user experience. If you add `useTransition` to `TabButton`, you can instead display the pending state in the tab button instead.
Notice that clicking “Posts” no longer replaces the entire tab container with a spinner:
App.jsTabButton.js
TabButton.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useTransition } from 'react';
export default function TabButton({ action, children, isActive }) {
const [isPending, startTransition] = useTransition();
if (isActive) {
return <b>{children}</b>
}
if (isPending) {
return <b className="pending">{children}</b>;
}
return (
<button onClick={() => {
startTransition(() => {
action();
});
}}>
{children}
</button>
);
}
```
Show more
[Read more about using Transitions with Suspense.](https://react.dev/reference/react/Suspense)
### Note
Transitions only “wait” long enough to avoid hiding *already revealed* content (like the tab container). If the Posts tab had a [nested `<Suspense>` boundary,](https://react.dev/reference/react/Suspense) the Transition would not “wait” for it.
* * *
### Building a Suspense-enabled router[Link for Building a Suspense-enabled router]()
If you’re building a React framework or a router, we recommend marking page navigations as Transitions.
```
function Router() {
const [page, setPage] = useState('/');
const [isPending, startTransition] = useTransition();
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
// ...
```
This is recommended for three reasons:
- [Transitions are interruptible,]() which lets the user click away without waiting for the re-render to complete.
- [Transitions prevent unwanted loading indicators,]() which lets the user avoid jarring jumps on navigation.
- [Transitions wait for all pending actions]() which lets the user wait for side effects to complete before the new page is shown.
Here is a simplified router example using Transitions for navigations.
App.jsLayout.jsIndexPage.jsArtistPage.jsAlbums.jsBiography.jsPanel.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState, useTransition } from 'react';
import IndexPage from './IndexPage.js';
import ArtistPage from './ArtistPage.js';
import Layout from './Layout.js';
export default function App() {
return (
<Suspense fallback={<BigSpinner />}>
<Router />
</Suspense>
);
}
function Router() {
const [page, setPage] = useState('/');
const [isPending, startTransition] = useTransition();
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
let content;
if (page === '/') {
content = (
<IndexPage navigate={navigate} />
);
} else if (page === '/the-beatles') {
content = (
<ArtistPage
artist={{
id: 'the-beatles',
name: 'The Beatles',
}}
/>
);
}
return (
<Layout isPending={isPending}>
{content}
</Layout>
);
}
function BigSpinner() {
return <h2>🌀 Loading...</h2>;
}
```
Show more
### Note
[Suspense-enabled](https://react.dev/reference/react/Suspense) routers are expected to wrap the navigation updates into Transitions by default.
* * *
### Displaying an error to users with an error boundary[Link for Displaying an error to users with an error boundary]()
If a function passed to `startTransition` throws an error, you can display an error to your user with an [error boundary](https://react.dev/reference/react/Component). To use an error boundary, wrap the component where you are calling the `useTransition` in an error boundary. Once the function passed to `startTransition` errors, the fallback for the error boundary will be displayed.
AddCommentContainer.js
AddCommentContainer.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useTransition } from "react";
import { ErrorBoundary } from "react-error-boundary";
export function AddCommentContainer() {
return (
<ErrorBoundary fallback={<p>⚠️Something went wrong</p>}>
<AddCommentButton />
</ErrorBoundary>
);
}
function addComment(comment) {
// For demonstration purposes to show Error Boundary
if (comment == null) {
throw new Error("Example Error: An error thrown to trigger error boundary");
}
}
function AddCommentButton() {
const [pending, startTransition] = useTransition();
return (
<button
disabled={pending}
onClick={() => {
startTransition(() => {
// Intentionally not passing a comment
// so error gets thrown
addComment();
});
}}
>
Add comment
</button>
);
}
```
Show more
* * *
## Troubleshooting[Link for Troubleshooting]()
### Updating an input in a Transition doesn’t work[Link for Updating an input in a Transition doesn’t work]()
You can’t use a Transition for a state variable that controls an input:
```
const [text, setText] = useState('');
// ...
function handleChange(e) {
// ❌ Can't use Transitions for controlled input state
startTransition(() => {
setText(e.target.value);
});
}
// ...
return <input value={text} onChange={handleChange} />;
```
This is because Transitions are non-blocking, but updating an input in response to the change event should happen synchronously. If you want to run a Transition in response to typing, you have two options:
1. You can declare two separate state variables: one for the input state (which always updates synchronously), and one that you will update in a Transition. This lets you control the input using the synchronous state, and pass the Transition state variable (which will “lag behind” the input) to the rest of your rendering logic.
2. Alternatively, you can have one state variable, and add [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue) which will “lag behind” the real value. It will trigger non-blocking re-renders to “catch up” with the new value automatically.
* * *
### React doesn’t treat my state update as a Transition[Link for React doesn’t treat my state update as a Transition]()
When you wrap a state update in a Transition, make sure that it happens *during* the `startTransition` call:
```
startTransition(() => {
// ✅ Setting state *during* startTransition call
setPage('/about');
});
```
The function you pass to `startTransition` must be synchronous. You can’t mark an update as a Transition like this:
```
startTransition(() => {
// ❌ Setting state *after* startTransition call
setTimeout(() => {
setPage('/about');
}, 1000);
});
```
Instead, you could do this:
```
setTimeout(() => {
startTransition(() => {
// ✅ Setting state *during* startTransition call
setPage('/about');
});
}, 1000);
```
* * *
### React doesn’t treat my state update after `await` as a Transition[Link for this heading]()
When you use `await` inside a `startTransition` function, the state updates that happen after the `await` are not marked as Transitions. You must wrap state updates after each `await` in a `startTransition` call:
```
startTransition(async () => {
await someAsyncFunction();
// ❌ Not using startTransition after await
setPage('/about');
});
```
However, this works instead:
```
startTransition(async () => {
await someAsyncFunction();
// ✅ Using startTransition *after* await
startTransition(() => {
setPage('/about');
});
});
```
This is a JavaScript limitation due to React losing the scope of the async context. In the future, when [AsyncContext](https://github.com/tc39/proposal-async-context) is available, this limitation will be removed.
* * *
### I want to call `useTransition` from outside a component[Link for this heading]()
You can’t call `useTransition` outside a component because it’s a Hook. In this case, use the standalone [`startTransition`](https://react.dev/reference/react/startTransition) method instead. It works the same way, but it doesn’t provide the `isPending` indicator.
* * *
### The function I pass to `startTransition` executes immediately[Link for this heading]()
If you run this code, it will print 1, 2, 3:
```
console.log(1);
startTransition(() => {
console.log(2);
setPage('/about');
});
console.log(3);
```
**It is expected to print 1, 2, 3.** The function you pass to `startTransition` does not get delayed. Unlike with the browser `setTimeout`, it does not run the callback later. React executes your function immediately, but any state updates scheduled *while it is running* are marked as Transitions. You can imagine that it works like this:
```
// A simplified version of how React works
let isInsideTransition = false;
function startTransition(scope) {
isInsideTransition = true;
scope();
isInsideTransition = false;
}
function setState() {
if (isInsideTransition) {
// ... schedule a Transition state update ...
} else {
// ... schedule an urgent state update ...
}
}
```
### My state updates in Transitions are out of order[Link for My state updates in Transitions are out of order]()
If you `await` inside `startTransition`, you might see the updates happen out of order.
In this example, the `updateQuantity` function simulates a request to the server to update the item’s quantity in the cart. This function *artificially returns the every other request after the previous* to simulate race conditions for network requests.
Try updating the quantity once, then update it quickly multiple times. You might see the incorrect total:
App.jsItem.jsTotal.jsapi.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useTransition } from "react";
import { updateQuantity } from "./api";
import Item from "./Item";
import Total from "./Total";
export default function App({}) {
const [quantity, setQuantity] = useState(1);
const [isPending, startTransition] = useTransition();
// Store the actual quantity in separate state to show the mismatch.
const [clientQuantity, setClientQuantity] = useState(1);
const updateQuantityAction = newQuantity => {
setClientQuantity(newQuantity);
// Access the pending state of the transition,
// by wrapping in startTransition again.
startTransition(async () => {
const savedQuantity = await updateQuantity(newQuantity);
startTransition(() => {
setQuantity(savedQuantity);
});
});
};
return (
<div>
<h1>Checkout</h1>
<Item action={updateQuantityAction}/>
<hr />
<Total clientQuantity={clientQuantity} savedQuantity={quantity} isPending={isPending} />
</div>
);
}
```
Show more
When clicking multiple times, it’s possible for previous requests to finish after later requests. When this happens, React currently has no way to know the intended order. This is because the updates are scheduled asynchronously, and React loses context of the order across the async boundary.
This is expected, because Actions within a Transition do not guarantee execution order. For common use cases, React provides higher-level abstractions like [`useActionState`](https://react.dev/reference/react/useActionState) and [`<form>` actions](https://react.dev/reference/react-dom/components/form) that handle ordering for you. For advanced use cases, you’ll need to implement your own queuing and abort logic to handle this.
[PrevioususeSyncExternalStore](https://react.dev/reference/react/useSyncExternalStore)
[NextComponents](https://react.dev/reference/react/components) |
https://react.dev/reference/react/apis | [API Reference](https://react.dev/reference/react)
# Built-in React APIs[Link for this heading]()
In addition to [Hooks](https://react.dev/reference/react) and [Components](https://react.dev/reference/react/components), the `react` package exports a few other APIs that are useful for defining components. This page lists all the remaining modern React APIs.
* * *
- [`createContext`](https://react.dev/reference/react/createContext) lets you define and provide context to the child components. Used with [`useContext`.](https://react.dev/reference/react/useContext)
- [`forwardRef`](https://react.dev/reference/react/forwardRef) lets your component expose a DOM node as a ref to the parent. Used with [`useRef`.](https://react.dev/reference/react/useRef)
- [`lazy`](https://react.dev/reference/react/lazy) lets you defer loading a component’s code until it’s rendered for the first time.
- [`memo`](https://react.dev/reference/react/memo) lets your component skip re-renders with same props. Used with [`useMemo`](https://react.dev/reference/react/useMemo) and [`useCallback`.](https://react.dev/reference/react/useCallback)
- [`startTransition`](https://react.dev/reference/react/startTransition) lets you mark a state update as non-urgent. Similar to [`useTransition`.](https://react.dev/reference/react/useTransition)
- [`act`](https://react.dev/reference/react/act) lets you wrap renders and interactions in tests to ensure updates have processed before making assertions.
* * *
## Resource APIs[Link for Resource APIs]()
*Resources* can be accessed by a component without having them as part of their state. For example, a component can read a message from a Promise or read styling information from a context.
To read a value from a resource, use this API:
- [`use`](https://react.dev/reference/react/use) lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](https://react.dev/learn/passing-data-deeply-with-context).
```
function MessageComponent({ messagePromise }) {
const message = use(messagePromise);
const theme = use(ThemeContext);
// ...
}
```
[Previous<Suspense>](https://react.dev/reference/react/Suspense)
[Nextact](https://react.dev/reference/react/act) |
https://react.dev/reference/react/cache | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# cache - This feature is available in the latest Canary[Link for this heading]()
### React Server Components
`cache` is only for use with [React Server Components](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023).
`cache` lets you cache the result of a data fetch or computation.
```
const cachedFn = cache(fn);
```
- [Reference]()
- [`cache(fn)`]()
- [Usage]()
- [Cache an expensive computation]()
- [Share a snapshot of data]()
- [Preload data]()
- [Troubleshooting]()
- [My memoized function still runs even though I’ve called it with the same arguments]()
* * *
## Reference[Link for Reference]()
### `cache(fn)`[Link for this heading]()
Call `cache` outside of any components to create a version of the function with caching.
```
import {cache} from 'react';
import calculateMetrics from 'lib/metrics';
const getMetrics = cache(calculateMetrics);
function Chart({data}) {
const report = getMetrics(data);
// ...
}
```
When `getMetrics` is first called with `data`, `getMetrics` will call `calculateMetrics(data)` and store the result in cache. If `getMetrics` is called again with the same `data`, it will return the cached result instead of calling `calculateMetrics(data)` again.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `fn`: The function you want to cache results for. `fn` can take any arguments and return any value.
#### Returns[Link for Returns]()
`cache` returns a cached version of `fn` with the same type signature. It does not call `fn` in the process.
When calling `cachedFn` with given arguments, it first checks if a cached result exists in the cache. If a cached result exists, it returns the result. If not, it calls `fn` with the arguments, stores the result in the cache, and returns the result. The only time `fn` is called is when there is a cache miss.
### Note
The optimization of caching return values based on inputs is known as [*memoization*](https://en.wikipedia.org/wiki/Memoization). We refer to the function returned from `cache` as a memoized function.
#### Caveats[Link for Caveats]()
- React will invalidate the cache for all memoized functions for each server request.
- Each call to `cache` creates a new function. This means that calling `cache` with the same function multiple times will return different memoized functions that do not share the same cache.
- `cachedFn` will also cache errors. If `fn` throws an error for certain arguments, it will be cached, and the same error is re-thrown when `cachedFn` is called with those same arguments.
- `cache` is for use in [Server Components](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023) only.
* * *
## Usage[Link for Usage]()
### Cache an expensive computation[Link for Cache an expensive computation]()
Use `cache` to skip duplicate work.
```
import {cache} from 'react';
import calculateUserMetrics from 'lib/user';
const getUserMetrics = cache(calculateUserMetrics);
function Profile({user}) {
const metrics = getUserMetrics(user);
// ...
}
function TeamReport({users}) {
for (let user in users) {
const metrics = getUserMetrics(user);
// ...
}
// ...
}
```
If the same `user` object is rendered in both `Profile` and `TeamReport`, the two components can share work and only call `calculateUserMetrics` once for that `user`.
Assume `Profile` is rendered first. It will call `getUserMetrics`, and check if there is a cached result. Since it is the first time `getUserMetrics` is called with that `user`, there will be a cache miss. `getUserMetrics` will then call `calculateUserMetrics` with that `user` and write the result to cache.
When `TeamReport` renders its list of `users` and reaches the same `user` object, it will call `getUserMetrics` and read the result from cache.
### Pitfall
##### Calling different memoized functions will read from different caches.[Link for Calling different memoized functions will read from different caches.]()
To access the same cache, components must call the same memoized function.
```
// Temperature.js
import {cache} from 'react';
import {calculateWeekReport} from './report';
export function Temperature({cityData}) {
// 🚩 Wrong: Calling `cache` in component creates new `getWeekReport` for each render
const getWeekReport = cache(calculateWeekReport);
const report = getWeekReport(cityData);
// ...
}
```
```
// Precipitation.js
import {cache} from 'react';
import {calculateWeekReport} from './report';
// 🚩 Wrong: `getWeekReport` is only accessible for `Precipitation` component.
const getWeekReport = cache(calculateWeekReport);
export function Precipitation({cityData}) {
const report = getWeekReport(cityData);
// ...
}
```
In the above example, `Precipitation` and `Temperature` each call `cache` to create a new memoized function with their own cache look-up. If both components render for the same `cityData`, they will do duplicate work to call `calculateWeekReport`.
In addition, `Temperature` creates a new memoized function each time the component is rendered which doesn’t allow for any cache sharing.
To maximize cache hits and reduce work, the two components should call the same memoized function to access the same cache. Instead, define the memoized function in a dedicated module that can be [`import`-ed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) across components.
```
// getWeekReport.js
import {cache} from 'react';
import {calculateWeekReport} from './report';
export default cache(calculateWeekReport);
```
```
// Temperature.js
import getWeekReport from './getWeekReport';
export default function Temperature({cityData}) {
const report = getWeekReport(cityData);
// ...
}
```
```
// Precipitation.js
import getWeekReport from './getWeekReport';
export default function Precipitation({cityData}) {
const report = getWeekReport(cityData);
// ...
}
```
Here, both components call the same memoized function exported from `./getWeekReport.js` to read and write to the same cache.
### Share a snapshot of data[Link for Share a snapshot of data]()
To share a snapshot of data between components, call `cache` with a data-fetching function like `fetch`. When multiple components make the same data fetch, only one request is made and the data returned is cached and shared across components. All components refer to the same snapshot of data across the server render.
```
import {cache} from 'react';
import {fetchTemperature} from './api.js';
const getTemperature = cache(async (city) => {
return await fetchTemperature(city);
});
async function AnimatedWeatherCard({city}) {
const temperature = await getTemperature(city);
// ...
}
async function MinimalWeatherCard({city}) {
const temperature = await getTemperature(city);
// ...
}
```
If `AnimatedWeatherCard` and `MinimalWeatherCard` both render for the same city, they will receive the same snapshot of data from the memoized function.
If `AnimatedWeatherCard` and `MinimalWeatherCard` supply different city arguments to `getTemperature`, then `fetchTemperature` will be called twice and each call site will receive different data.
The city acts as a cache key.
### Note
Asynchronous rendering is only supported for Server Components.
```
async function AnimatedWeatherCard({city}) {
const temperature = await getTemperature(city);
// ...
}
```
### Preload data[Link for Preload data]()
By caching a long-running data fetch, you can kick off asynchronous work prior to rendering the component.
```
const getUser = cache(async (id) => {
return await db.user.query(id);
});
async function Profile({id}) {
const user = await getUser(id);
return (
<section>
<img src={user.profilePic} />
<h2>{user.name}</h2>
</section>
);
}
function Page({id}) {
// ✅ Good: start fetching the user data
getUser(id);
// ... some computational work
return (
<>
<Profile id={id} />
</>
);
}
```
When rendering `Page`, the component calls `getUser` but note that it doesn’t use the returned data. This early `getUser` call kicks off the asynchronous database query that occurs while `Page` is doing other computational work and rendering children.
When rendering `Profile`, we call `getUser` again. If the initial `getUser` call has already returned and cached the user data, when `Profile` asks and waits for this data, it can simply read from the cache without requiring another remote procedure call. If the initial data request hasn’t been completed, preloading data in this pattern reduces delay in data-fetching.
##### Deep Dive
#### Caching asynchronous work[Link for Caching asynchronous work]()
Show Details
When evaluating an [asynchronous function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function), you will receive a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) for that work. The promise holds the state of that work (*pending*, *fulfilled*, *failed*) and its eventual settled result.
In this example, the asynchronous function `fetchData` returns a promise that is awaiting the `fetch`.
```
async function fetchData() {
return await fetch(`https://...`);
}
const getData = cache(fetchData);
async function MyComponent() {
getData();
// ... some computational work
await getData();
// ...
}
```
In calling `getData` the first time, the promise returned from `fetchData` is cached. Subsequent look-ups will then return the same promise.
Notice that the first `getData` call does not `await` whereas the second does. [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) is a JavaScript operator that will wait and return the settled result of the promise. The first `getData` call simply initiates the `fetch` to cache the promise for the second `getData` to look-up.
If by the second call the promise is still *pending*, then `await` will pause for the result. The optimization is that while we wait on the `fetch`, React can continue with computational work, thus reducing the wait time for the second call.
If the promise is already settled, either to an error or the *fulfilled* result, `await` will return that value immediately. In both outcomes, there is a performance benefit.
### Pitfall
##### Calling a memoized function outside of a component will not use the cache.[Link for Calling a memoized function outside of a component will not use the cache.]()
```
import {cache} from 'react';
const getUser = cache(async (userId) => {
return await db.user.query(userId);
});
// 🚩 Wrong: Calling memoized function outside of component will not memoize.
getUser('demo-id');
async function DemoProfile() {
// ✅ Good: `getUser` will memoize.
const user = await getUser('demo-id');
return <Profile user={user} />;
}
```
React only provides cache access to the memoized function in a component. When calling `getUser` outside of a component, it will still evaluate the function but not read or update the cache.
This is because cache access is provided through a [context](https://react.dev/learn/passing-data-deeply-with-context) which is only accessible from a component.
##### Deep Dive
#### When should I use `cache`, [`memo`](https://react.dev/reference/react/memo), or [`useMemo`](https://react.dev/reference/react/useMemo)?[Link for this heading]()
Show Details
All mentioned APIs offer memoization but the difference is what they’re intended to memoize, who can access the cache, and when their cache is invalidated.
#### `useMemo`[Link for this heading]()
In general, you should use [`useMemo`](https://react.dev/reference/react/useMemo) for caching a expensive computation in a Client Component across renders. As an example, to memoize a transformation of data within a component.
```
'use client';
function WeatherReport({record}) {
const avgTemp = useMemo(() => calculateAvg(record), record);
// ...
}
function App() {
const record = getRecord();
return (
<>
<WeatherReport record={record} />
<WeatherReport record={record} />
</>
);
}
```
In this example, `App` renders two `WeatherReport`s with the same record. Even though both components do the same work, they cannot share work. `useMemo`’s cache is only local to the component.
However, `useMemo` does ensure that if `App` re-renders and the `record` object doesn’t change, each component instance would skip work and use the memoized value of `avgTemp`. `useMemo` will only cache the last computation of `avgTemp` with the given dependencies.
#### `cache`[Link for this heading]()
In general, you should use `cache` in Server Components to memoize work that can be shared across components.
```
const cachedFetchReport = cache(fetchReport);
function WeatherReport({city}) {
const report = cachedFetchReport(city);
// ...
}
function App() {
const city = "Los Angeles";
return (
<>
<WeatherReport city={city} />
<WeatherReport city={city} />
</>
);
}
```
Re-writing the previous example to use `cache`, in this case the second instance of `WeatherReport` will be able to skip duplicate work and read from the same cache as the first `WeatherReport`. Another difference from the previous example is that `cache` is also recommended for memoizing data fetches, unlike `useMemo` which should only be used for computations.
At this time, `cache` should only be used in Server Components and the cache will be invalidated across server requests.
#### `memo`[Link for this heading]()
You should use [`memo`](https://react.dev/reference/react/memo) to prevent a component re-rendering if its props are unchanged.
```
'use client';
function WeatherReport({record}) {
const avgTemp = calculateAvg(record);
// ...
}
const MemoWeatherReport = memo(WeatherReport);
function App() {
const record = getRecord();
return (
<>
<MemoWeatherReport record={record} />
<MemoWeatherReport record={record} />
</>
);
}
```
In this example, both `MemoWeatherReport` components will call `calculateAvg` when first rendered. However, if `App` re-renders, with no changes to `record`, none of the props have changed and `MemoWeatherReport` will not re-render.
Compared to `useMemo`, `memo` memoizes the component render based on props vs. specific computations. Similar to `useMemo`, the memoized component only caches the last render with the last prop values. Once the props change, the cache invalidates and the component re-renders.
* * *
## Troubleshooting[Link for Troubleshooting]()
### My memoized function still runs even though I’ve called it with the same arguments[Link for My memoized function still runs even though I’ve called it with the same arguments]()
See prior mentioned pitfalls
- [Calling different memoized functions will read from different caches.]()
- [Calling a memoized function outside of a component will not use the cache.]()
If none of the above apply, it may be a problem with how React checks if something exists in cache.
If your arguments are not [primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) (ex. objects, functions, arrays), ensure you’re passing the same object reference.
When calling a memoized function, React will look up the input arguments to see if a result is already cached. React will use shallow equality of the arguments to determine if there is a cache hit.
```
import {cache} from 'react';
const calculateNorm = cache((vector) => {
// ...
});
function MapMarker(props) {
// 🚩 Wrong: props is an object that changes every render.
const length = calculateNorm(props);
// ...
}
function App() {
return (
<>
<MapMarker x={10} y={10} z={10} />
<MapMarker x={10} y={10} z={10} />
</>
);
}
```
In this case the two `MapMarker`s look like they’re doing the same work and calling `calculateNorm` with the same value of `{x: 10, y: 10, z:10}`. Even though the objects contain the same values, they are not the same object reference as each component creates its own `props` object.
React will call [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) on the input to verify if there is a cache hit.
```
import {cache} from 'react';
const calculateNorm = cache((x, y, z) => {
// ...
});
function MapMarker(props) {
// ✅ Good: Pass primitives to memoized function
const length = calculateNorm(props.x, props.y, props.z);
// ...
}
function App() {
return (
<>
<MapMarker x={10} y={10} z={10} />
<MapMarker x={10} y={10} z={10} />
</>
);
}
```
One way to address this could be to pass the vector dimensions to `calculateNorm`. This works because the dimensions themselves are primitives.
Another solution may be to pass the vector object itself as a prop to the component. We’ll need to pass the same object to both component instances.
```
import {cache} from 'react';
const calculateNorm = cache((vector) => {
// ...
});
function MapMarker(props) {
// ✅ Good: Pass the same `vector` object
const length = calculateNorm(props.vector);
// ...
}
function App() {
const vector = [10, 10, 10];
return (
<>
<MapMarker vector={vector} />
<MapMarker vector={vector} />
</>
);
}
```
[Previousact](https://react.dev/reference/react/act)
[NextcreateContext](https://react.dev/reference/react/createContext) |
https://react.dev/reference/react/useOptimistic | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react/hooks)
# useOptimistic[Link for this heading]()
`useOptimistic` is a React Hook that lets you optimistically update the UI.
```
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
```
- [Reference]()
- [`useOptimistic(state, updateFn)`]()
- [Usage]()
- [Optimistically updating forms]()
* * *
## Reference[Link for Reference]()
### `useOptimistic(state, updateFn)`[Link for this heading]()
`useOptimistic` is a React Hook that lets you show a different state while an async action is underway. It accepts some state as an argument and returns a copy of that state that can be different during the duration of an async action such as a network request. You provide a function that takes the current state and the input to the action, and returns the optimistic state to be used while the action is pending.
This state is called the “optimistic” state because it is usually used to immediately present the user with the result of performing an action, even though the action actually takes time to complete.
```
import { useOptimistic } from 'react';
function AppContainer() {
const [optimisticState, addOptimistic] = useOptimistic(
state,
// updateFn
(currentState, optimisticValue) => {
// merge and return new state
// with optimistic value
}
);
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `state`: the value to be returned initially and whenever no action is pending.
- `updateFn(currentState, optimisticValue)`: a function that takes the current state and the optimistic value passed to `addOptimistic` and returns the resulting optimistic state. It must be a pure function. `updateFn` takes in two parameters. The `currentState` and the `optimisticValue`. The return value will be the merged value of the `currentState` and `optimisticValue`.
#### Returns[Link for Returns]()
- `optimisticState`: The resulting optimistic state. It is equal to `state` unless an action is pending, in which case it is equal to the value returned by `updateFn`.
- `addOptimistic`: `addOptimistic` is the dispatching function to call when you have an optimistic update. It takes one argument, `optimisticValue`, of any type and will call the `updateFn` with `state` and `optimisticValue`.
* * *
## Usage[Link for Usage]()
### Optimistically updating forms[Link for Optimistically updating forms]()
The `useOptimistic` Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server’s response to reflect the changes, the interface is immediately updated with the expected outcome.
For example, when a user types a message into the form and hits the “Send” button, the `useOptimistic` Hook allows the message to immediately appear in the list with a “Sending…” label, even before the message is actually sent to a server. This “optimistic” approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the “Sending…” label is removed.
App.jsactions.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useOptimistic, useState, useRef } from "react";
import { deliverMessage } from "./actions.js";
function Thread({ messages, sendMessage }) {
const formRef = useRef();
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
formRef.current.reset();
await sendMessage(formData);
}
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, newMessage) => [
...state,
{
text: newMessage,
sending: true
}
]
);
return (
<>
{optimisticMessages.map((message, index) => (
<div key={index}>
{message.text}
{!!message.sending && <small> (Sending...)</small>}
</div>
))}
<form action={formAction} ref={formRef}>
<input type="text" name="message" placeholder="Hello!" />
<button type="submit">Send</button>
</form>
</>
);
}
export default function App() {
const [messages, setMessages] = useState([
{ text: "Hello there!", sending: false, key: 1 }
]);
async function sendMessage(formData) {
const sentMessage = await deliverMessage(formData.get("message"));
setMessages((messages) => [...messages, { text: sentMessage }]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}
```
Show more
[PrevioususeMemo](https://react.dev/reference/react/useMemo)
[NextuseReducer](https://react.dev/reference/react/useReducer) |
https://react.dev/reference/react/Suspense | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react/components)
# <Suspense>[Link for this heading]()
`<Suspense>` lets you display a fallback until its children have finished loading.
```
<Suspense fallback={<Loading />}>
<SomeComponent />
</Suspense>
```
- [Reference]()
- [`<Suspense>`]()
- [Usage]()
- [Displaying a fallback while content is loading]()
- [Revealing content together at once]()
- [Revealing nested content as it loads]()
- [Showing stale content while fresh content is loading]()
- [Preventing already revealed content from hiding]()
- [Indicating that a Transition is happening]()
- [Resetting Suspense boundaries on navigation]()
- [Providing a fallback for server errors and client-only content]()
- [Troubleshooting]()
- [How do I prevent the UI from being replaced by a fallback during an update?]()
* * *
## Reference[Link for Reference]()
### `<Suspense>`[Link for this heading]()
#### Props[Link for Props]()
- `children`: The actual UI you intend to render. If `children` suspends while rendering, the Suspense boundary will switch to rendering `fallback`.
- `fallback`: An alternate UI to render in place of the actual UI if it has not finished loading. Any valid React node is accepted, though in practice, a fallback is a lightweight placeholder view, such as a loading spinner or skeleton. Suspense will automatically switch to `fallback` when `children` suspends, and back to `children` when the data is ready. If `fallback` suspends while rendering, it will activate the closest parent Suspense boundary.
#### Caveats[Link for Caveats]()
- React does not preserve any state for renders that got suspended before they were able to mount for the first time. When the component has loaded, React will retry rendering the suspended tree from scratch.
- If Suspense was displaying content for the tree, but then it suspended again, the `fallback` will be shown again unless the update causing it was caused by [`startTransition`](https://react.dev/reference/react/startTransition) or [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue).
- If React needs to hide the already visible content because it suspended again, it will clean up [layout Effects](https://react.dev/reference/react/useLayoutEffect) in the content tree. When the content is ready to be shown again, React will fire the layout Effects again. This ensures that Effects measuring the DOM layout don’t try to do this while the content is hidden.
- React includes under-the-hood optimizations like *Streaming Server Rendering* and *Selective Hydration* that are integrated with Suspense. Read [an architectural overview](https://github.com/reactwg/react-18/discussions/37) and watch [a technical talk](https://www.youtube.com/watch?v=pj5N-Khihgc) to learn more.
* * *
## Usage[Link for Usage]()
### Displaying a fallback while content is loading[Link for Displaying a fallback while content is loading]()
You can wrap any part of your application with a Suspense boundary:
```
<Suspense fallback={<Loading />}>
<Albums />
</Suspense>
```
React will display your loading fallback until all the code and data needed by the children has been loaded.
In the example below, the `Albums` component *suspends* while fetching the list of albums. Until it’s ready to render, React switches the closest Suspense boundary above to show the fallback—your `Loading` component. Then, when the data loads, React hides the `Loading` fallback and renders the `Albums` component with data.
ArtistPage.jsAlbums.js
ArtistPage.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense } from 'react';
import Albums from './Albums.js';
export default function ArtistPage({ artist }) {
return (
<>
<h1>{artist.name}</h1>
<Suspense fallback={<Loading />}>
<Albums artistId={artist.id} />
</Suspense>
</>
);
}
function Loading() {
return <h2>🌀 Loading...</h2>;
}
```
Show more
### Note
**Only Suspense-enabled data sources will activate the Suspense component.** They include:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming)
- Lazy-loading component code with [`lazy`](https://react.dev/reference/react/lazy)
- Reading the value of a cached Promise with [`use`](https://react.dev/reference/react/use)
Suspense **does not** detect when data is fetched inside an Effect or event handler.
The exact way you would load data in the `Albums` component above depends on your framework. If you use a Suspense-enabled framework, you’ll find the details in its data fetching documentation.
Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React.
* * *
### Revealing content together at once[Link for Revealing content together at once]()
By default, the whole tree inside Suspense is treated as a single unit. For example, even if *only one* of these components suspends waiting for some data, *all* of them together will be replaced by the loading indicator:
```
<Suspense fallback={<Loading />}>
<Biography />
<Panel>
<Albums />
</Panel>
</Suspense>
```
Then, after all of them are ready to be displayed, they will all appear together at once.
In the example below, both `Biography` and `Albums` fetch some data. However, because they are grouped under a single Suspense boundary, these components always “pop in” together at the same time.
ArtistPage.jsPanel.jsBiography.jsAlbums.js
ArtistPage.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense } from 'react';
import Albums from './Albums.js';
import Biography from './Biography.js';
import Panel from './Panel.js';
export default function ArtistPage({ artist }) {
return (
<>
<h1>{artist.name}</h1>
<Suspense fallback={<Loading />}>
<Biography artistId={artist.id} />
<Panel>
<Albums artistId={artist.id} />
</Panel>
</Suspense>
</>
);
}
function Loading() {
return <h2>🌀 Loading...</h2>;
}
```
Show more
Components that load data don’t have to be direct children of the Suspense boundary. For example, you can move `Biography` and `Albums` into a new `Details` component. This doesn’t change the behavior. `Biography` and `Albums` share the same closest parent Suspense boundary, so their reveal is coordinated together.
```
<Suspense fallback={<Loading />}>
<Details artistId={artist.id} />
</Suspense>
function Details({ artistId }) {
return (
<>
<Biography artistId={artistId} />
<Panel>
<Albums artistId={artistId} />
</Panel>
</>
);
}
```
* * *
### Revealing nested content as it loads[Link for Revealing nested content as it loads]()
When a component suspends, the closest parent Suspense component shows the fallback. This lets you nest multiple Suspense components to create a loading sequence. Each Suspense boundary’s fallback will be filled in as the next level of content becomes available. For example, you can give the album list its own fallback:
```
<Suspense fallback={<BigSpinner />}>
<Biography />
<Suspense fallback={<AlbumsGlimmer />}>
<Panel>
<Albums />
</Panel>
</Suspense>
</Suspense>
```
With this change, displaying the `Biography` doesn’t need to “wait” for the `Albums` to load.
The sequence will be:
1. If `Biography` hasn’t loaded yet, `BigSpinner` is shown in place of the entire content area.
2. Once `Biography` finishes loading, `BigSpinner` is replaced by the content.
3. If `Albums` hasn’t loaded yet, `AlbumsGlimmer` is shown in place of `Albums` and its parent `Panel`.
4. Finally, once `Albums` finishes loading, it replaces `AlbumsGlimmer`.
ArtistPage.jsPanel.jsBiography.jsAlbums.js
ArtistPage.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense } from 'react';
import Albums from './Albums.js';
import Biography from './Biography.js';
import Panel from './Panel.js';
export default function ArtistPage({ artist }) {
return (
<>
<h1>{artist.name}</h1>
<Suspense fallback={<BigSpinner />}>
<Biography artistId={artist.id} />
<Suspense fallback={<AlbumsGlimmer />}>
<Panel>
<Albums artistId={artist.id} />
</Panel>
</Suspense>
</Suspense>
</>
);
}
function BigSpinner() {
return <h2>🌀 Loading...</h2>;
}
function AlbumsGlimmer() {
return (
<div className="glimmer-panel">
<div className="glimmer-line" />
<div className="glimmer-line" />
<div className="glimmer-line" />
</div>
);
}
```
Show more
Suspense boundaries let you coordinate which parts of your UI should always “pop in” together at the same time, and which parts should progressively reveal more content in a sequence of loading states. You can add, move, or delete Suspense boundaries in any place in the tree without affecting the rest of your app’s behavior.
Don’t put a Suspense boundary around every component. Suspense boundaries should not be more granular than the loading sequence that you want the user to experience. If you work with a designer, ask them where the loading states should be placed—it’s likely that they’ve already included them in their design wireframes.
* * *
### Showing stale content while fresh content is loading[Link for Showing stale content while fresh content is loading]()
In this example, the `SearchResults` component suspends while fetching the search results. Type `"a"`, wait for the results, and then edit it to `"ab"`. The results for `"a"` will get replaced by the loading fallback.
App.jsSearchResults.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState } from 'react';
import SearchResults from './SearchResults.js';
export default function App() {
const [query, setQuery] = useState('');
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<SearchResults query={query} />
</Suspense>
</>
);
}
```
Show more
A common alternative UI pattern is to *defer* updating the list and to keep showing the previous results until the new results are ready. The [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue) Hook lets you pass a deferred version of the query down:
```
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<SearchResults query={deferredQuery} />
</Suspense>
</>
);
}
```
The `query` will update immediately, so the input will display the new value. However, the `deferredQuery` will keep its previous value until the data has loaded, so `SearchResults` will show the stale results for a bit.
To make it more obvious to the user, you can add a visual indication when the stale result list is displayed:
```
<div style={{
opacity: query !== deferredQuery ? 0.5 : 1
}}>
<SearchResults query={deferredQuery} />
</div>
```
Enter `"a"` in the example below, wait for the results to load, and then edit the input to `"ab"`. Notice how instead of the Suspense fallback, you now see the dimmed stale result list until the new results have loaded:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState, useDeferredValue } from 'react';
import SearchResults from './SearchResults.js';
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<div style={{ opacity: isStale ? 0.5 : 1 }}>
<SearchResults query={deferredQuery} />
</div>
</Suspense>
</>
);
}
```
Show more
### Note
Both deferred values and [Transitions]() let you avoid showing Suspense fallback in favor of inline indicators. Transitions mark the whole update as non-urgent so they are typically used by frameworks and router libraries for navigation. Deferred values, on the other hand, are mostly useful in application code where you want to mark a part of UI as non-urgent and let it “lag behind” the rest of the UI.
* * *
### Preventing already revealed content from hiding[Link for Preventing already revealed content from hiding]()
When a component suspends, the closest parent Suspense boundary switches to showing the fallback. This can lead to a jarring user experience if it was already displaying some content. Try pressing this button:
App.jsLayout.jsIndexPage.jsArtistPage.jsAlbums.jsBiography.jsPanel.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState } from 'react';
import IndexPage from './IndexPage.js';
import ArtistPage from './ArtistPage.js';
import Layout from './Layout.js';
export default function App() {
return (
<Suspense fallback={<BigSpinner />}>
<Router />
</Suspense>
);
}
function Router() {
const [page, setPage] = useState('/');
function navigate(url) {
setPage(url);
}
let content;
if (page === '/') {
content = (
<IndexPage navigate={navigate} />
);
} else if (page === '/the-beatles') {
content = (
<ArtistPage
artist={{
id: 'the-beatles',
name: 'The Beatles',
}}
/>
);
}
return (
<Layout>
{content}
</Layout>
);
}
function BigSpinner() {
return <h2>🌀 Loading...</h2>;
}
```
Show more
When you pressed the button, the `Router` component rendered `ArtistPage` instead of `IndexPage`. A component inside `ArtistPage` suspended, so the closest Suspense boundary started showing the fallback. The closest Suspense boundary was near the root, so the whole site layout got replaced by `BigSpinner`.
To prevent this, you can mark the navigation state update as a *Transition* with [`startTransition`:](https://react.dev/reference/react/startTransition)
```
function Router() {
const [page, setPage] = useState('/');
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
// ...
```
This tells React that the state transition is not urgent, and it’s better to keep showing the previous page instead of hiding any already revealed content. Now clicking the button “waits” for the `Biography` to load:
App.jsLayout.jsIndexPage.jsArtistPage.jsAlbums.jsBiography.jsPanel.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, startTransition, useState } from 'react';
import IndexPage from './IndexPage.js';
import ArtistPage from './ArtistPage.js';
import Layout from './Layout.js';
export default function App() {
return (
<Suspense fallback={<BigSpinner />}>
<Router />
</Suspense>
);
}
function Router() {
const [page, setPage] = useState('/');
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
let content;
if (page === '/') {
content = (
<IndexPage navigate={navigate} />
);
} else if (page === '/the-beatles') {
content = (
<ArtistPage
artist={{
id: 'the-beatles',
name: 'The Beatles',
}}
/>
);
}
return (
<Layout>
{content}
</Layout>
);
}
function BigSpinner() {
return <h2>🌀 Loading...</h2>;
}
```
Show more
A Transition doesn’t wait for *all* content to load. It only waits long enough to avoid hiding already revealed content. For example, the website `Layout` was already revealed, so it would be bad to hide it behind a loading spinner. However, the nested `Suspense` boundary around `Albums` is new, so the Transition doesn’t wait for it.
### Note
Suspense-enabled routers are expected to wrap the navigation updates into Transitions by default.
* * *
### Indicating that a Transition is happening[Link for Indicating that a Transition is happening]()
In the above example, once you click the button, there is no visual indication that a navigation is in progress. To add an indicator, you can replace [`startTransition`](https://react.dev/reference/react/startTransition) with [`useTransition`](https://react.dev/reference/react/useTransition) which gives you a boolean `isPending` value. In the example below, it’s used to change the website header styling while a Transition is happening:
App.jsLayout.jsIndexPage.jsArtistPage.jsAlbums.jsBiography.jsPanel.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Suspense, useState, useTransition } from 'react';
import IndexPage from './IndexPage.js';
import ArtistPage from './ArtistPage.js';
import Layout from './Layout.js';
export default function App() {
return (
<Suspense fallback={<BigSpinner />}>
<Router />
</Suspense>
);
}
function Router() {
const [page, setPage] = useState('/');
const [isPending, startTransition] = useTransition();
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
let content;
if (page === '/') {
content = (
<IndexPage navigate={navigate} />
);
} else if (page === '/the-beatles') {
content = (
<ArtistPage
artist={{
id: 'the-beatles',
name: 'The Beatles',
}}
/>
);
}
return (
<Layout isPending={isPending}>
{content}
</Layout>
);
}
function BigSpinner() {
return <h2>🌀 Loading...</h2>;
}
```
Show more
* * *
### Resetting Suspense boundaries on navigation[Link for Resetting Suspense boundaries on navigation]()
During a Transition, React will avoid hiding already revealed content. However, if you navigate to a route with different parameters, you might want to tell React it is *different* content. You can express this with a `key`:
```
<ProfilePage key={queryParams.id} />
```
Imagine you’re navigating within a user’s profile page, and something suspends. If that update is wrapped in a Transition, it will not trigger the fallback for already visible content. That’s the expected behavior.
However, now imagine you’re navigating between two different user profiles. In that case, it makes sense to show the fallback. For example, one user’s timeline is *different content* from another user’s timeline. By specifying a `key`, you ensure that React treats different users’ profiles as different components, and resets the Suspense boundaries during navigation. Suspense-integrated routers should do this automatically.
* * *
### Providing a fallback for server errors and client-only content[Link for Providing a fallback for server errors and client-only content]()
If you use one of the [streaming server rendering APIs](https://react.dev/reference/react-dom/server) (or a framework that relies on them), React will also use your `<Suspense>` boundaries to handle errors on the server. If a component throws an error on the server, React will not abort the server render. Instead, it will find the closest `<Suspense>` component above it and include its fallback (such as a spinner) into the generated server HTML. The user will see a spinner at first.
On the client, React will attempt to render the same component again. If it errors on the client too, React will throw the error and display the closest [error boundary.](https://react.dev/reference/react/Component) However, if it does not error on the client, React will not display the error to the user since the content was eventually displayed successfully.
You can use this to opt out some components from rendering on the server. To do this, throw an error in the server environment and then wrap them in a `<Suspense>` boundary to replace their HTML with fallbacks:
```
<Suspense fallback={<Loading />}>
<Chat />
</Suspense>
function Chat() {
if (typeof window === 'undefined') {
throw Error('Chat should only render on the client.');
}
// ...
}
```
The server HTML will include the loading indicator. It will be replaced by the `Chat` component on the client.
* * *
## Troubleshooting[Link for Troubleshooting]()
### How do I prevent the UI from being replaced by a fallback during an update?[Link for How do I prevent the UI from being replaced by a fallback during an update?]()
Replacing visible UI with a fallback creates a jarring user experience. This can happen when an update causes a component to suspend, and the nearest Suspense boundary is already showing content to the user.
To prevent this from happening, [mark the update as non-urgent using `startTransition`](). During a Transition, React will wait until enough data has loaded to prevent an unwanted fallback from appearing:
```
function handleNextPageClick() {
// If this update suspends, don't hide the already displayed content
startTransition(() => {
setCurrentPage(currentPage + 1);
});
}
```
This will avoid hiding existing content. However, any newly rendered `Suspense` boundaries will still immediately display fallbacks to avoid blocking the UI and let the user see the content as it becomes available.
**React will only prevent unwanted fallbacks during non-urgent updates**. It will not delay a render if it’s the result of an urgent update. You must opt in with an API like [`startTransition`](https://react.dev/reference/react/startTransition) or [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue).
If your router is integrated with Suspense, it should wrap its updates into [`startTransition`](https://react.dev/reference/react/startTransition) automatically.
[Previous<StrictMode>](https://react.dev/reference/react/StrictMode)
[NextAPIs](https://react.dev/reference/react/apis) |
https://react.dev/reference/react/components | [API Reference](https://react.dev/reference/react)
# Built-in React Components[Link for this heading]()
React exposes a few built-in components that you can use in your JSX.
* * *
## Built-in components[Link for Built-in components]()
- [`<Fragment>`](https://react.dev/reference/react/Fragment), alternatively written as `<>...</>`, lets you group multiple JSX nodes together.
- [`<Profiler>`](https://react.dev/reference/react/Profiler) lets you measure rendering performance of a React tree programmatically.
- [`<Suspense>`](https://react.dev/reference/react/Suspense) lets you display a fallback while the child components are loading.
- [`<StrictMode>`](https://react.dev/reference/react/StrictMode) enables extra development-only checks that help you find bugs early.
* * *
## Your own components[Link for Your own components]()
You can also [define your own components](https://react.dev/learn/your-first-component) as JavaScript functions.
[PrevioususeTransition](https://react.dev/reference/react/useTransition)
[Next<Fragment> (<>)](https://react.dev/reference/react/Fragment) |
https://react.dev/reference/react/act | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# act[Link for this heading]()
`act` is a test helper to apply pending React updates before making assertions.
```
await act(async actFn)
```
To prepare a component for assertions, wrap the code rendering it and performing updates inside an `await act()` call. This makes your test run closer to how React works in the browser.
### Note
You might find using `act()` directly a bit too verbose. To avoid some of the boilerplate, you could use a library like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), whose helpers are wrapped with `act()`.
- [Reference]()
- [`await act(async actFn)`]()
- [Usage]()
- [Rendering components in tests]()
- [Dispatching events in tests]()
- [Troubleshooting]()
- [I’m getting an error: “The current testing environment is not configured to support act”(…)”]()
* * *
## Reference[Link for Reference]()
### `await act(async actFn)`[Link for this heading]()
When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. React provides a helper called `act()` that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions.
The name `act` comes from the [Arrange-Act-Assert](https://wiki.c2.com/?ArrangeActAssert) pattern.
```
it ('renders with button disabled', async () => {
await act(async () => {
root.render(<TestComponent />)
});
expect(container.querySelector('button')).toBeDisabled();
});
```
### Note
We recommend using `act` with `await` and an `async` function. Although the sync version works in many cases, it doesn’t work in all cases and due to the way React schedules updates internally, it’s difficult to predict when you can use the sync version.
We will deprecate and remove the sync version in the future.
#### Parameters[Link for Parameters]()
- `async actFn`: An async function wrapping renders or interactions for components being tested. Any updates triggered within the `actFn`, are added to an internal act queue, which are then flushed together to process and apply any changes to the DOM. Since it is async, React will also run any code that crosses an async boundary, and flush any updates scheduled.
#### Returns[Link for Returns]()
`act` does not return anything.
## Usage[Link for Usage]()
When testing a component, you can use `act` to make assertions about its output.
For example, let’s say we have this `Counter` component, the usage examples below show how to test it:
```
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(prev => prev + 1);
}
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</div>
)
}
```
### Rendering components in tests[Link for Rendering components in tests]()
To test the render output of a component, wrap the render inside `act()`:
```
import {act} from 'react';
import ReactDOMClient from 'react-dom/client';
import Counter from './Counter';
it('can render and update a counter', async () => {
container = document.createElement('div');
document.body.appendChild(container);
// ✅ Render the component inside act().
await act(() => {
ReactDOMClient.createRoot(container).render(<Counter />);
});
const button = container.querySelector('button');
const label = container.querySelector('p');
expect(label.textContent).toBe('You clicked 0 times');
expect(document.title).toBe('You clicked 0 times');
});
```
Here, we create a container, append it to the document, and render the `Counter` component inside `act()`. This ensures that the component is rendered and its effects are applied before making assertions.
Using `act` ensures that all updates have been applied before we make assertions.
### Dispatching events in tests[Link for Dispatching events in tests]()
To test events, wrap the event dispatch inside `act()`:
```
import {act} from 'react';
import ReactDOMClient from 'react-dom/client';
import Counter from './Counter';
it.only('can render and update a counter', async () => {
const container = document.createElement('div');
document.body.appendChild(container);
await act( async () => {
ReactDOMClient.createRoot(container).render(<Counter />);
});
// ✅ Dispatch the event inside act().
await act(async () => {
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
const button = container.querySelector('button');
const label = container.querySelector('p');
expect(label.textContent).toBe('You clicked 1 times');
expect(document.title).toBe('You clicked 1 times');
});
```
Here, we render the component with `act`, and then dispatch the event inside another `act()`. This ensures that all updates from the event are applied before making assertions.
### Pitfall
Don’t forget that dispatching DOM events only works when the DOM container is added to the document. You can use a library like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) to reduce the boilerplate code.
## Troubleshooting[Link for Troubleshooting]()
### I’m getting an error: “The current testing environment is not configured to support act”(…)”[Link for I’m getting an error: “The current testing environment is not configured to support act”(…)”]()
Using `act` requires setting `global.IS_REACT_ACT_ENVIRONMENT=true` in your test environment. This is to ensure that `act` is only used in the correct environment.
If you don’t set the global, you will see an error like this:
Console
Warning: The current testing environment is not configured to support act(…)
To fix, add this to your global setup file for React tests:
```
global.IS_REACT_ACT_ENVIRONMENT=true
```
### Note
In testing frameworks like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), `IS_REACT_ACT_ENVIRONMENT` is already set for you.
[PreviousAPIs](https://react.dev/reference/react/apis)
[Nextcache](https://react.dev/reference/react/cache) |
https://react.dev/reference/react/createContext | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# createContext[Link for this heading]()
`createContext` lets you create a [context](https://react.dev/learn/passing-data-deeply-with-context) that components can provide or read.
```
const SomeContext = createContext(defaultValue)
```
- [Reference]()
- [`createContext(defaultValue)`]()
- [`SomeContext.Provider`]()
- [`SomeContext.Consumer`]()
- [Usage]()
- [Creating context]()
- [Importing and exporting context from a file]()
- [Troubleshooting]()
- [I can’t find a way to change the context value]()
* * *
## Reference[Link for Reference]()
### `createContext(defaultValue)`[Link for this heading]()
Call `createContext` outside of any components to create a context.
```
import { createContext } from 'react';
const ThemeContext = createContext('light');
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `defaultValue`: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don’t have any meaningful default value, specify `null`. The default value is meant as a “last resort” fallback. It is static and never changes over time.
#### Returns[Link for Returns]()
`createContext` returns a context object.
**The context object itself does not hold any information.** It represents *which* context other components read or provide. Typically, you will use [`SomeContext.Provider`]() in components above to specify the context value, and call [`useContext(SomeContext)`](https://react.dev/reference/react/useContext) in components below to read it. The context object has a few properties:
- `SomeContext.Provider` lets you provide the context value to components.
- `SomeContext.Consumer` is an alternative and rarely used way to read the context value.
* * *
### `SomeContext.Provider`[Link for this heading]()
Wrap your components into a context provider to specify the value of this context for all components inside:
```
function App() {
const [theme, setTheme] = useState('light');
// ...
return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}
```
#### Props[Link for Props]()
- `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](https://react.dev/reference/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it.
* * *
### `SomeContext.Consumer`[Link for this heading]()
Before `useContext` existed, there was an older way to read context:
```
function Button() {
// 🟡 Legacy way (not recommended)
return (
<ThemeContext.Consumer>
{theme => (
<button className={theme} />
)}
</ThemeContext.Consumer>
);
}
```
Although this older way still works, **newly written code should read context with [`useContext()`](https://react.dev/reference/react/useContext) instead:**
```
function Button() {
// ✅ Recommended way
const theme = useContext(ThemeContext);
return <button className={theme} />;
}
```
#### Props[Link for Props]()
- `children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](https://react.dev/reference/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context from the parent components changes.
* * *
## Usage[Link for Usage]()
### Creating context[Link for Creating context]()
Context lets components [pass information deep down](https://react.dev/learn/passing-data-deeply-with-context) without explicitly passing props.
Call `createContext` outside any components to create one or more contexts.
```
import { createContext } from 'react';
const ThemeContext = createContext('light');
const AuthContext = createContext(null);
```
`createContext` returns a context object. Components can read context by passing it to [`useContext()`](https://react.dev/reference/react/useContext):
```
function Button() {
const theme = useContext(ThemeContext);
// ...
}
function Profile() {
const currentUser = useContext(AuthContext);
// ...
}
```
By default, the values they receive will be the default values you have specified when creating the contexts. However, by itself this isn’t useful because the default values never change.
Context is useful because you can **provide other, dynamic values from your components:**
```
function App() {
const [theme, setTheme] = useState('dark');
const [currentUser, setCurrentUser] = useState({ name: 'Taylor' });
// ...
return (
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={currentUser}>
<Page />
</AuthContext.Provider>
</ThemeContext.Provider>
);
}
```
Now the `Page` component and any components inside it, no matter how deep, will “see” the passed context values. If the passed context values change, React will re-render the components reading the context as well.
[Read more about reading and providing context and see examples.](https://react.dev/reference/react/useContext)
* * *
### Importing and exporting context from a file[Link for Importing and exporting context from a file]()
Often, components in different files will need access to the same context. This is why it’s common to declare contexts in a separate file. Then you can use the [`export` statement](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to make context available for other files:
```
// Contexts.js
import { createContext } from 'react';
export const ThemeContext = createContext('light');
export const AuthContext = createContext(null);
```
Components declared in other files can then use the [`import`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import) statement to read or provide this context:
```
// Button.js
import { ThemeContext } from './Contexts.js';
function Button() {
const theme = useContext(ThemeContext);
// ...
}
```
```
// App.js
import { ThemeContext, AuthContext } from './Contexts.js';
function App() {
// ...
return (
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={currentUser}>
<Page />
</AuthContext.Provider>
</ThemeContext.Provider>
);
}
```
This works similar to [importing and exporting components.](https://react.dev/learn/importing-and-exporting-components)
* * *
## Troubleshooting[Link for Troubleshooting]()
### I can’t find a way to change the context value[Link for I can’t find a way to change the context value]()
Code like this specifies the *default* context value:
```
const ThemeContext = createContext('light');
```
This value never changes. React only uses this value as a fallback if it can’t find a matching provider above.
To make context change over time, [add state and wrap components in a context provider.](https://react.dev/reference/react/useContext)
[Previouscache](https://react.dev/reference/react/cache)
[Nextlazy](https://react.dev/reference/react/lazy) |
https://react.dev/reference/react/startTransition | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# startTransition[Link for this heading]()
`startTransition` lets you render a part of the UI in the background.
```
startTransition(action)
```
- [Reference]()
- [`startTransition(action)`]()
- [Usage]()
- [Marking a state update as a non-blocking Transition]()
* * *
## Reference[Link for Reference]()
### `startTransition(action)`[Link for this heading]()
The `startTransition` function lets you mark a state update as a Transition.
```
import { startTransition } from 'react';
function TabContainer() {
const [tab, setTab] = useState('about');
function selectTab(nextTab) {
startTransition(() => {
setTab(nextTab);
});
}
// ...
}
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `action`: A function that updates some state by calling one or more [`set` functions](https://react.dev/reference/react/useState). React calls `action` immediately with no parameters and marks all state updates scheduled synchronously during the `action` function call as Transitions. Any async calls awaited in the `action` will be included in the transition, but currently require wrapping any `set` functions after the `await` in an additional `startTransition` (see [Troubleshooting](https://react.dev/reference/react/useTransition)). State updates marked as Transitions will be [non-blocking]() and [will not display unwanted loading indicators.](https://react.dev/reference/react/useTransition).
#### Returns[Link for Returns]()
`startTransition` does not return anything.
#### Caveats[Link for Caveats]()
- `startTransition` does not provide a way to track whether a Transition is pending. To show a pending indicator while the Transition is ongoing, you need [`useTransition`](https://react.dev/reference/react/useTransition) instead.
- You can wrap an update into a Transition only if you have access to the `set` function of that state. If you want to start a Transition in response to some prop or a custom Hook return value, try [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue) instead.
- The function you pass to `startTransition` is called immediately, marking all state updates that happen while it executes as Transitions. If you try to perform state updates in a `setTimeout`, for example, they won’t be marked as Transitions.
- You must wrap any state updates after any async requests in another `startTransition` to mark them as Transitions. This is a known limitation that we will fix in the future (see [Troubleshooting](https://react.dev/reference/react/useTransition)).
- A state update marked as a Transition will be interrupted by other state updates. For example, if you update a chart component inside a Transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input state update.
- Transition updates can’t be used to control text inputs.
- If there are multiple ongoing Transitions, React currently batches them together. This is a limitation that may be removed in a future release.
* * *
## Usage[Link for Usage]()
### Marking a state update as a non-blocking Transition[Link for Marking a state update as a non-blocking Transition]()
You can mark a state update as a *Transition* by wrapping it in a `startTransition` call:
```
import { startTransition } from 'react';
function TabContainer() {
const [tab, setTab] = useState('about');
function selectTab(nextTab) {
startTransition(() => {
setTab(nextTab);
});
}
// ...
}
```
Transitions let you keep the user interface updates responsive even on slow devices.
With a Transition, your UI stays responsive in the middle of a re-render. For example, if the user clicks a tab but then change their mind and click another tab, they can do that without waiting for the first re-render to finish.
### Note
`startTransition` is very similar to [`useTransition`](https://react.dev/reference/react/useTransition), except that it does not provide the `isPending` flag to track whether a Transition is ongoing. You can call `startTransition` when `useTransition` is not available. For example, `startTransition` works outside components, such as from a data library.
[Learn about Transitions and see examples on the `useTransition` page.](https://react.dev/reference/react/useTransition)
[Previousmemo](https://react.dev/reference/react/memo)
[Nextuse](https://react.dev/reference/react/use) |
https://react.dev/reference/react/lazy | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# lazy[Link for this heading]()
`lazy` lets you defer loading component’s code until it is rendered for the first time.
```
const SomeComponent = lazy(load)
```
- [Reference]()
- [`lazy(load)`]()
- [`load` function]()
- [Usage]()
- [Lazy-loading components with Suspense]()
- [Troubleshooting]()
- [My `lazy` component’s state gets reset unexpectedly]()
* * *
## Reference[Link for Reference]()
### `lazy(load)`[Link for this heading]()
Call `lazy` outside your components to declare a lazy-loaded React component:
```
import { lazy } from 'react';
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `load`: A function that returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or another *thenable* (a Promise-like object with a `then` method). React will not call `load` until the first time you attempt to render the returned component. After React first calls `load`, it will wait for it to resolve, and then render the resolved value’s `.default` as a React component. Both the returned Promise and the Promise’s resolved value will be cached, so React will not call `load` more than once. If the Promise rejects, React will `throw` the rejection reason for the nearest Error Boundary to handle.
#### Returns[Link for Returns]()
`lazy` returns a React component you can render in your tree. While the code for the lazy component is still loading, attempting to render it will *suspend.* Use [`<Suspense>`](https://react.dev/reference/react/Suspense) to display a loading indicator while it’s loading.
* * *
### `load` function[Link for this heading]()
#### Parameters[Link for Parameters]()
`load` receives no parameters.
#### Returns[Link for Returns]()
You need to return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or some other *thenable* (a Promise-like object with a `then` method). It needs to eventually resolve to an object whose `.default` property is a valid React component type, such as a function, [`memo`](https://react.dev/reference/react/memo), or a [`forwardRef`](https://react.dev/reference/react/forwardRef) component.
* * *
## Usage[Link for Usage]()
### Lazy-loading components with Suspense[Link for Lazy-loading components with Suspense]()
Usually, you import components with the static [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) declaration:
```
import MarkdownPreview from './MarkdownPreview.js';
```
To defer loading this component’s code until it’s rendered for the first time, replace this import with:
```
import { lazy } from 'react';
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
```
This code relies on [dynamic `import()`,](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) which might require support from your bundler or framework. Using this pattern requires that the lazy component you’re importing was exported as the `default` export.
Now that your component’s code loads on demand, you also need to specify what should be displayed while it is loading. You can do this by wrapping the lazy component or any of its parents into a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary:
```
<Suspense fallback={<Loading />}>
<h2>Preview</h2>
<MarkdownPreview />
</Suspense>
```
In this example, the code for `MarkdownPreview` won’t be loaded until you attempt to render it. If `MarkdownPreview` hasn’t loaded yet, `Loading` will be shown in its place. Try ticking the checkbox:
App.jsLoading.jsMarkdownPreview.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, Suspense, lazy } from 'react';
import Loading from './Loading.js';
const MarkdownPreview = lazy(() => delayForDemo(import('./MarkdownPreview.js')));
export default function MarkdownEditor() {
const [showPreview, setShowPreview] = useState(false);
const [markdown, setMarkdown] = useState('Hello, **world**!');
return (
<>
<textarea value={markdown} onChange={e => setMarkdown(e.target.value)} />
<label>
<input type="checkbox" checked={showPreview} onChange={e => setShowPreview(e.target.checked)} />
Show preview
</label>
<hr />
{showPreview && (
<Suspense fallback={<Loading />}>
<h2>Preview</h2>
<MarkdownPreview markdown={markdown} />
</Suspense>
)}
</>
);
}
// Add a fixed delay so you can see the loading state
function delayForDemo(promise) {
return new Promise(resolve => {
setTimeout(resolve, 2000);
}).then(() => promise);
}
```
Show more
This demo loads with an artificial delay. The next time you untick and tick the checkbox, `Preview` will be cached, so there will be no loading state. To see the loading state again, click “Reset” on the sandbox.
[Learn more about managing loading states with Suspense.](https://react.dev/reference/react/Suspense)
* * *
## Troubleshooting[Link for Troubleshooting]()
### My `lazy` component’s state gets reset unexpectedly[Link for this heading]()
Do not declare `lazy` components *inside* other components:
```
import { lazy } from 'react';
function Editor() {
// 🔴 Bad: This will cause all state to be reset on re-renders
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
// ...
}
```
Instead, always declare them at the top level of your module:
```
import { lazy } from 'react';
// ✅ Good: Declare lazy components outside of your components
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
function Editor() {
// ...
}
```
[PreviouscreateContext](https://react.dev/reference/react/createContext)
[Nextmemo](https://react.dev/reference/react/memo) |
https://react.dev/reference/react/experimental_taintUniqueValue | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# experimental\_taintUniqueValue[Link for this heading]()
### Under Construction
**This API is experimental and is not available in a stable version of React yet.**
You can try it by upgrading React packages to the most recent experimental version:
- `react@experimental`
- `react-dom@experimental`
- `eslint-plugin-react-hooks@experimental`
Experimental versions of React may contain bugs. Don’t use them in production.
This API is only available inside [React Server Components](https://react.dev/reference/rsc/use-client).
`taintUniqueValue` lets you prevent unique values from being passed to Client Components like passwords, keys, or tokens.
```
taintUniqueValue(errMessage, lifetime, value)
```
To prevent passing an object containing sensitive data, see [`taintObjectReference`](https://react.dev/reference/react/experimental_taintObjectReference).
- [Reference]()
- [`taintUniqueValue(message, lifetime, value)`]()
- [Usage]()
- [Prevent a token from being passed to Client Components]()
* * *
## Reference[Link for Reference]()
### `taintUniqueValue(message, lifetime, value)`[Link for this heading]()
Call `taintUniqueValue` with a password, token, key or hash to register it with React as something that should not be allowed to be passed to the Client as is:
```
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass secret keys to the client.',
process,
process.env.SECRET_KEY
);
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `message`: The message you want to display if `value` is passed to a Client Component. This message will be displayed as a part of the Error that will be thrown if `value` is passed to a Client Component.
- `lifetime`: Any object that indicates how long `value` should be tainted. `value` will be blocked from being sent to any Client Component while this object still exists. For example, passing `globalThis` blocks the value for the lifetime of an app. `lifetime` is typically an object whose properties contains `value`.
- `value`: A string, bigint or TypedArray. `value` must be a unique sequence of characters or bytes with high entropy such as a cryptographic token, private key, hash, or a long password. `value` will be blocked from being sent to any Client Component.
#### Returns[Link for Returns]()
`experimental_taintUniqueValue` returns `undefined`.
#### Caveats[Link for Caveats]()
- Deriving new values from tainted values can compromise tainting protection. New values created by uppercasing tainted values, concatenating tainted string values into a larger string, converting tainted values to base64, substringing tainted values, and other similar transformations are not tainted unless you explicitly call `taintUniqueValue` on these newly created values.
- Do not use `taintUniqueValue` to protect low-entropy values such as PIN codes or phone numbers. If any value in a request is controlled by an attacker, they could infer which value is tainted by enumerating all possible values of the secret.
* * *
## Usage[Link for Usage]()
### Prevent a token from being passed to Client Components[Link for Prevent a token from being passed to Client Components]()
To ensure that sensitive information such as passwords, session tokens, or other unique values do not inadvertently get passed to Client Components, the `taintUniqueValue` function provides a layer of protection. When a value is tainted, any attempt to pass it to a Client Component will result in an error.
The `lifetime` argument defines the duration for which the value remains tainted. For values that should remain tainted indefinitely, objects like [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) or `process` can serve as the `lifetime` argument. These objects have a lifespan that spans the entire duration of your app’s execution.
```
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass a user password to the client.',
globalThis,
process.env.SECRET_KEY
);
```
If the tainted value’s lifespan is tied to a object, the `lifetime` should be the object that encapsulates the value. This ensures the tainted value remains protected for the lifetime of the encapsulating object.
```
import {experimental_taintUniqueValue} from 'react';
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
experimental_taintUniqueValue(
'Do not pass a user session token to the client.',
user,
user.session.token
);
return user;
}
```
In this example, the `user` object serves as the `lifetime` argument. If this object gets stored in a global cache or is accessible by another request, the session token remains tainted.
### Pitfall
**Do not rely solely on tainting for security.** Tainting a value doesn’t block every possible derived value. For example, creating a new value by upper casing a tainted string will not taint the new value.
```
import {experimental_taintUniqueValue} from 'react';
const password = 'correct horse battery staple';
experimental_taintUniqueValue(
'Do not pass the password to the client.',
globalThis,
password
);
const uppercasePassword = password.toUpperCase() // `uppercasePassword` is not tainted
```
In this example, the constant `password` is tainted. Then `password` is used to create a new value `uppercasePassword` by calling the `toUpperCase` method on `password`. The newly created `uppercasePassword` is not tainted.
Other similar ways of deriving new values from tainted values like concatenating it into a larger string, converting it to base64, or returning a substring create untained values.
Tainting only protects against simple mistakes like explicitly passing secret values to the client. Mistakes in calling the `taintUniqueValue` like using a global store outside of React, without the corresponding lifetime object, can cause the tainted value to become untainted. Tainting is a layer of protection; a secure app will have multiple layers of protection, well designed APIs, and isolation patterns.
##### Deep Dive
#### Using `server-only` and `taintUniqueValue` to prevent leaking secrets[Link for this heading]()
Show Details
If you’re running a Server Components environment that has access to private keys or passwords such as database passwords, you have to be careful not to pass that to a Client Component.
```
export async function Dashboard(props) {
// DO NOT DO THIS
return <Overview password={process.env.API_PASSWORD} />;
}
```
```
"use client";
import {useEffect} from '...'
export async function Overview({ password }) {
useEffect(() => {
const headers = { Authorization: password };
fetch(url, { headers }).then(...);
}, [password]);
...
}
```
This example would leak the secret API token to the client. If this API token can be used to access data this particular user shouldn’t have access to, it could lead to a data breach.
Ideally, secrets like this are abstracted into a single helper file that can only be imported by trusted data utilities on the server. The helper can even be tagged with [`server-only`](https://www.npmjs.com/package/server-only) to ensure that this file isn’t imported on the client.
```
import "server-only";
export function fetchAPI(url) {
const headers = { Authorization: process.env.API_PASSWORD };
return fetch(url, { headers });
}
```
Sometimes mistakes happen during refactoring and not all of your colleagues might know about this. To protect against this mistakes happening down the line we can “taint” the actual password:
```
import "server-only";
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass the API token password to the client. ' +
'Instead do all fetches on the server.'
process,
process.env.API_PASSWORD
);
```
Now whenever anyone tries to pass this password to a Client Component, or send the password to a Client Component with a Server Function, an error will be thrown with message you defined when you called `taintUniqueValue`.
* * *
[Previousexperimental\_taintObjectReference](https://react.dev/reference/react/experimental_taintObjectReference) |
https://react.dev/reference/react/experimental_taintObjectReference | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# experimental\_taintObjectReference[Link for this heading]()
### Under Construction
**This API is experimental and is not available in a stable version of React yet.**
You can try it by upgrading React packages to the most recent experimental version:
- `react@experimental`
- `react-dom@experimental`
- `eslint-plugin-react-hooks@experimental`
Experimental versions of React may contain bugs. Don’t use them in production.
This API is only available inside React Server Components.
`taintObjectReference` lets you prevent a specific object instance from being passed to a Client Component like a `user` object.
```
experimental_taintObjectReference(message, object);
```
To prevent passing a key, hash or token, see [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue).
- [Reference]()
- [`taintObjectReference(message, object)`]()
- [Usage]()
- [Prevent user data from unintentionally reaching the client]()
* * *
## Reference[Link for Reference]()
### `taintObjectReference(message, object)`[Link for this heading]()
Call `taintObjectReference` with an object to register it with React as something that should not be allowed to be passed to the Client as is:
```
import {experimental_taintObjectReference} from 'react';
experimental_taintObjectReference(
'Do not pass ALL environment variables to the client.',
process.env
);
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `message`: The message you want to display if the object gets passed to a Client Component. This message will be displayed as a part of the Error that will be thrown if the object gets passed to a Client Component.
- `object`: The object to be tainted. Functions and class instances can be passed to `taintObjectReference` as `object`. Functions and classes are already blocked from being passed to Client Components but the React’s default error message will be replaced by what you defined in `message`. When a specific instance of a Typed Array is passed to `taintObjectReference` as `object`, any other copies of the Typed Array will not be tainted.
#### Returns[Link for Returns]()
`experimental_taintObjectReference` returns `undefined`.
#### Caveats[Link for Caveats]()
- Recreating or cloning a tainted object creates a new untainted object which may contain sensitive data. For example, if you have a tainted `user` object, `const userInfo = {name: user.name, ssn: user.ssn}` or `{...user}` will create new objects which are not tainted. `taintObjectReference` only protects against simple mistakes when the object is passed through to a Client Component unchanged.
### Pitfall
**Do not rely on just tainting for security.** Tainting an object doesn’t prevent leaking of every possible derived value. For example, the clone of a tainted object will create a new untainted object. Using data from a tainted object (e.g. `{secret: taintedObj.secret}`) will create a new value or object that is not tainted. Tainting is a layer of protection; a secure app will have multiple layers of protection, well designed APIs, and isolation patterns.
* * *
## Usage[Link for Usage]()
### Prevent user data from unintentionally reaching the client[Link for Prevent user data from unintentionally reaching the client]()
A Client Component should never accept objects that carry sensitive data. Ideally, the data fetching functions should not expose data that the current user should not have access to. Sometimes mistakes happen during refactoring. To protect against these mistakes happening down the line we can “taint” the user object in our data API.
```
import {experimental_taintObjectReference} from 'react';
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
experimental_taintObjectReference(
'Do not pass the entire user object to the client. ' +
'Instead, pick off the specific properties you need for this use case.',
user,
);
return user;
}
```
Now whenever anyone tries to pass this object to a Client Component, an error will be thrown with the passed in error message instead.
##### Deep Dive
#### Protecting against leaks in data fetching[Link for Protecting against leaks in data fetching]()
Show Details
If you’re running a Server Components environment that has access to sensitive data, you have to be careful not to pass objects straight through:
```
// api.js
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
return user;
}
```
```
import { getUser } from 'api.js';
import { InfoCard } from 'components.js';
export async function Profile(props) {
const user = await getUser(props.userId);
// DO NOT DO THIS
return <InfoCard user={user} />;
}
```
```
// components.js
"use client";
export async function InfoCard({ user }) {
return <div>{user.name}</div>;
}
```
Ideally, the `getUser` should not expose data that the current user should not have access to. To prevent passing the `user` object to a Client Component down the line we can “taint” the user object:
```
// api.js
import {experimental_taintObjectReference} from 'react';
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
experimental_taintObjectReference(
'Do not pass the entire user object to the client. ' +
'Instead, pick off the specific properties you need for this use case.',
user,
);
return user;
}
```
Now if anyone tries to pass the `user` object to a Client Component, an error will be thrown with the passed in error message.
[Previoususe](https://react.dev/reference/react/use)
[Nextexperimental\_taintUniqueValue](https://react.dev/reference/react/experimental_taintUniqueValue) |
https://react.dev/reference/react/use | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# use[Link for this heading]()
`use` is a React API that lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](https://react.dev/learn/passing-data-deeply-with-context).
```
const value = use(resource);
```
- [Reference]()
- [`use(resource)`]()
- [Usage]()
- [Reading context with `use`]()
- [Streaming data from the server to the client]()
- [Dealing with rejected Promises]()
- [Troubleshooting]()
- [“Suspense Exception: This is not a real error!”]()
* * *
## Reference[Link for Reference]()
### `use(resource)`[Link for this heading]()
Call `use` in your component to read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](https://react.dev/learn/passing-data-deeply-with-context).
```
import { use } from 'react';
function MessageComponent({ messagePromise }) {
const message = use(messagePromise);
const theme = use(ThemeContext);
// ...
```
Unlike React Hooks, `use` can be called within loops and conditional statements like `if`. Like React Hooks, the function that calls `use` must be a Component or Hook.
When called with a Promise, the `use` API integrates with [`Suspense`](https://react.dev/reference/react/Suspense) and [error boundaries](https://react.dev/reference/react/Component). The component calling `use` *suspends* while the Promise passed to `use` is pending. If the component that calls `use` is wrapped in a Suspense boundary, the fallback will be displayed. Once the Promise is resolved, the Suspense fallback is replaced by the rendered components using the data returned by the `use` API. If the Promise passed to `use` is rejected, the fallback of the nearest Error Boundary will be displayed.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `resource`: this is the source of the data you want to read a value from. A resource can be a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a [context](https://react.dev/learn/passing-data-deeply-with-context).
#### Returns[Link for Returns]()
The `use` API returns the value that was read from the resource like the resolved value of a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](https://react.dev/learn/passing-data-deeply-with-context).
#### Caveats[Link for Caveats]()
- The `use` API must be called inside a Component or a Hook.
- When fetching data in a [Server Component](https://react.dev/reference/rsc/server-components), prefer `async` and `await` over `use`. `async` and `await` pick up rendering from the point where `await` was invoked, whereas `use` re-renders the component after the data is resolved.
- Prefer creating Promises in [Server Components](https://react.dev/reference/rsc/server-components) and passing them to [Client Components](https://react.dev/reference/rsc/use-client) over creating Promises in Client Components. Promises created in Client Components are recreated on every render. Promises passed from a Server Component to a Client Component are stable across re-renders. [See this example]().
* * *
## Usage[Link for Usage]()
### Reading context with `use`[Link for this heading]()
When a [context](https://react.dev/learn/passing-data-deeply-with-context) is passed to `use`, it works similarly to [`useContext`](https://react.dev/reference/react/useContext). While `useContext` must be called at the top level of your component, `use` can be called inside conditionals like `if` and loops like `for`. `use` is preferred over `useContext` because it is more flexible.
```
import { use } from 'react';
function Button() {
const theme = use(ThemeContext);
// ...
```
`use` returns the context value for the context you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context.
To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider.
```
function MyPage() {
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>
);
}
function Form() {
// ... renders buttons inside ...
}
```
It doesn’t matter how many layers of components there are between the provider and the `Button`. When a `Button` *anywhere* inside of `Form` calls `use(ThemeContext)`, it will receive `"dark"` as the value.
Unlike [`useContext`](https://react.dev/reference/react/useContext), `use` can be called in conditionals and loops like `if`.
```
function HorizontalRule({ show }) {
if (show) {
const theme = use(ThemeContext);
return <hr className={theme} />;
}
return false;
}
```
`use` is called from inside a `if` statement, allowing you to conditionally read values from a Context.
### Pitfall
Like `useContext`, `use(context)` always looks for the closest context provider *above* the component that calls it. It searches upwards and **does not** consider context providers in the component from which you’re calling `use(context)`.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createContext, use } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() {
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>
)
}
function Form() {
return (
<Panel title="Welcome">
<Button show={true}>Sign up</Button>
<Button show={false}>Log in</Button>
</Panel>
);
}
function Panel({ title, children }) {
const theme = use(ThemeContext);
const className = 'panel-' + theme;
return (
<section className={className}>
<h1>{title}</h1>
{children}
</section>
)
}
function Button({ show, children }) {
if (show) {
const theme = use(ThemeContext);
const className = 'button-' + theme;
return (
<button className={className}>
{children}
</button>
);
}
return false
}
```
Show more
### Streaming data from the server to the client[Link for Streaming data from the server to the client]()
Data can be streamed from the server to the client by passing a Promise as a prop from a Server Component to a Client Component.
```
import { fetchMessage } from './lib.js';
import { Message } from './message.js';
export default function App() {
const messagePromise = fetchMessage();
return (
<Suspense fallback={<p>waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}
```
The Client Component then takes the Promise it received as a prop and passes it to the `use` API. This allows the Client Component to read the value from the Promise that was initially created by the Server Component.
```
// message.js
'use client';
import { use } from 'react';
export function Message({ messagePromise }) {
const messageContent = use(messagePromise);
return <p>Here is the message: {messageContent}</p>;
}
```
Because `Message` is wrapped in [`Suspense`](https://react.dev/reference/react/Suspense), the fallback will be displayed until the Promise is resolved. When the Promise is resolved, the value will be read by the `use` API and the `Message` component will replace the Suspense fallback.
message.js
message.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
"use client";
import { use, Suspense } from "react";
function Message({ messagePromise }) {
const messageContent = use(messagePromise);
return <p>Here is the message: {messageContent}</p>;
}
export function MessageContainer({ messagePromise }) {
return (
<Suspense fallback={<p>⌛Downloading message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}
```
Show more
### Note
When passing a Promise from a Server Component to a Client Component, its resolved value must be serializable to pass between server and client. Data types like functions aren’t serializable and cannot be the resolved value of such a Promise.
##### Deep Dive
#### Should I resolve a Promise in a Server or Client Component?[Link for Should I resolve a Promise in a Server or Client Component?]()
Show Details
A Promise can be passed from a Server Component to a Client Component and resolved in the Client Component with the `use` API. You can also resolve the Promise in a Server Component with `await` and pass the required data to the Client Component as a prop.
```
export default async function App() {
const messageContent = await fetchMessage();
return <Message messageContent={messageContent} />
}
```
But using `await` in a [Server Component](https://react.dev/reference/react/components) will block its rendering until the `await` statement is finished. Passing a Promise from a Server Component to a Client Component prevents the Promise from blocking the rendering of the Server Component.
### Dealing with rejected Promises[Link for Dealing with rejected Promises]()
In some cases a Promise passed to `use` could be rejected. You can handle rejected Promises by either:
1. [Displaying an error to users with an error boundary.]()
2. [Providing an alternative value with `Promise.catch`]()
### Pitfall
`use` cannot be called in a try-catch block. Instead of a try-catch block [wrap your component in an Error Boundary](), or [provide an alternative value to use with the Promise’s `.catch` method]().
#### Displaying an error to users with an error boundary[Link for Displaying an error to users with an error boundary]()
If you’d like to display an error to your users when a Promise is rejected, you can use an [error boundary](https://react.dev/reference/react/Component). To use an error boundary, wrap the component where you are calling the `use` API in an error boundary. If the Promise passed to `use` is rejected the fallback for the error boundary will be displayed.
message.js
message.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
"use client";
import { use, Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";
export function MessageContainer({ messagePromise }) {
return (
<ErrorBoundary fallback={<p>⚠️Something went wrong</p>}>
<Suspense fallback={<p>⌛Downloading message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</ErrorBoundary>
);
}
function Message({ messagePromise }) {
const content = use(messagePromise);
return <p>Here is the message: {content}</p>;
}
```
Show more
#### Providing an alternative value with `Promise.catch`[Link for this heading]()
If you’d like to provide an alternative value when the Promise passed to `use` is rejected you can use the Promise’s [`catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) method.
```
import { Message } from './message.js';
export default function App() {
const messagePromise = new Promise((resolve, reject) => {
reject();
}).catch(() => {
return "no new message found.";
});
return (
<Suspense fallback={<p>waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}
```
To use the Promise’s `catch` method, call `catch` on the Promise object. `catch` takes a single argument: a function that takes an error message as an argument. Whatever is returned by the function passed to `catch` will be used as the resolved value of the Promise.
* * *
## Troubleshooting[Link for Troubleshooting]()
### “Suspense Exception: This is not a real error!”[Link for “Suspense Exception: This is not a real error!”]()
You are either calling `use` outside of a React Component or Hook function, or calling `use` in a try–catch block. If you are calling `use` inside a try–catch block, wrap your component in an error boundary, or call the Promise’s `catch` to catch the error and resolve the Promise with another value. [See these examples]().
If you are calling `use` outside a React Component or Hook function, move the `use` call to a React Component or Hook function.
```
function MessageComponent({messagePromise}) {
function download() {
// ❌ the function calling `use` is not a Component or Hook
const message = use(messagePromise);
// ...
```
Instead, call `use` outside any component closures, where the function that calls `use` is a Component or Hook.
```
function MessageComponent({messagePromise}) {
// ✅ `use` is being called from a component.
const message = use(messagePromise);
// ...
```
[PreviousstartTransition](https://react.dev/reference/react/startTransition)
[Nextexperimental\_taintObjectReference](https://react.dev/reference/react/experimental_taintObjectReference) |
https://react.dev/reference/react/memo | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react/apis)
# memo[Link for this heading]()
`memo` lets you skip re-rendering a component when its props are unchanged.
```
const MemoizedComponent = memo(SomeComponent, arePropsEqual?)
```
- [Reference]()
- [`memo(Component, arePropsEqual?)`]()
- [Usage]()
- [Skipping re-rendering when props are unchanged]()
- [Updating a memoized component using state]()
- [Updating a memoized component using a context]()
- [Minimizing props changes]()
- [Specifying a custom comparison function]()
- [Troubleshooting]()
- [My component re-renders when a prop is an object, array, or function]()
* * *
## Reference[Link for Reference]()
### `memo(Component, arePropsEqual?)`[Link for this heading]()
Wrap a component in `memo` to get a *memoized* version of that component. This memoized version of your component will usually not be re-rendered when its parent component is re-rendered as long as its props have not changed. But React may still re-render it: memoization is a performance optimization, not a guarantee.
```
import { memo } from 'react';
const SomeComponent = memo(function SomeComponent(props) {
// ...
});
```
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `Component`: The component that you want to memoize. The `memo` does not modify this component, but returns a new, memoized component instead. Any valid React component, including functions and [`forwardRef`](https://react.dev/reference/react/forwardRef) components, is accepted.
- **optional** `arePropsEqual`: A function that accepts two arguments: the component’s previous props, and its new props. It should return `true` if the old and new props are equal: that is, if the component will render the same output and behave in the same way with the new props as with the old. Otherwise it should return `false`. Usually, you will not specify this function. By default, React will compare each prop with [`Object.is`.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
#### Returns[Link for Returns]()
`memo` returns a new React component. It behaves the same as the component provided to `memo` except that React will not always re-render it when its parent is being re-rendered unless its props have changed.
* * *
## Usage[Link for Usage]()
### Skipping re-rendering when props are unchanged[Link for Skipping re-rendering when props are unchanged]()
React normally re-renders a component whenever its parent re-renders. With `memo`, you can create a component that React will not re-render when its parent re-renders so long as its new props are the same as the old props. Such a component is said to be *memoized*.
To memoize a component, wrap it in `memo` and use the value that it returns in place of your original component:
```
const Greeting = memo(function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
});
export default Greeting;
```
A React component should always have [pure rendering logic.](https://react.dev/learn/keeping-components-pure) This means that it must return the same output if its props, state, and context haven’t changed. By using `memo`, you are telling React that your component complies with this requirement, so React doesn’t need to re-render as long as its props haven’t changed. Even with `memo`, your component will re-render if its own state changes or if a context that it’s using changes.
In this example, notice that the `Greeting` component re-renders whenever `name` is changed (because that’s one of its props), but not when `address` is changed (because it’s not passed to `Greeting` as a prop):
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { memo, useState } from 'react';
export default function MyApp() {
const [name, setName] = useState('');
const [address, setAddress] = useState('');
return (
<>
<label>
Name{': '}
<input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Address{': '}
<input value={address} onChange={e => setAddress(e.target.value)} />
</label>
<Greeting name={name} />
</>
);
}
const Greeting = memo(function Greeting({ name }) {
console.log("Greeting was rendered at", new Date().toLocaleTimeString());
return <h3>Hello{name && ', '}{name}!</h3>;
});
```
Show more
### Note
**You should only rely on `memo` as a performance optimization.** If your code doesn’t work without it, find the underlying problem and fix it first. Then you may add `memo` to improve performance.
##### Deep Dive
#### Should you add memo everywhere?[Link for Should you add memo everywhere?]()
Show Details
If your app is like this site, and most interactions are coarse (like replacing a page or an entire section), memoization is usually unnecessary. On the other hand, if your app is more like a drawing editor, and most interactions are granular (like moving shapes), then you might find memoization very helpful.
Optimizing with `memo` is only valuable when your component re-renders often with the same exact props, and its re-rendering logic is expensive. If there is no perceptible lag when your component re-renders, `memo` is unnecessary. Keep in mind that `memo` is completely useless if the props passed to your component are *always different,* such as if you pass an object or a plain function defined during rendering. This is why you will often need [`useMemo`](https://react.dev/reference/react/useMemo) and [`useCallback`](https://react.dev/reference/react/useCallback) together with `memo`.
There is no benefit to wrapping a component in `memo` in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside of this approach is that code becomes less readable. Also, not all memoization is effective: a single value that’s “always new” is enough to break memoization for an entire component.
**In practice, you can make a lot of memoization unnecessary by following a few principles:**
1. When a component visually wraps other components, let it [accept JSX as children.](https://react.dev/learn/passing-props-to-a-component) This way, when the wrapper component updates its own state, React knows that its children don’t need to re-render.
2. Prefer local state and don’t [lift state up](https://react.dev/learn/sharing-state-between-components) any further than necessary. For example, don’t keep transient state like forms and whether an item is hovered at the top of your tree or in a global state library.
3. Keep your [rendering logic pure.](https://react.dev/learn/keeping-components-pure) If re-rendering a component causes a problem or produces some noticeable visual artifact, it’s a bug in your component! Fix the bug instead of adding memoization.
4. Avoid [unnecessary Effects that update state.](https://react.dev/learn/you-might-not-need-an-effect) Most performance problems in React apps are caused by chains of updates originating from Effects that cause your components to render over and over.
5. Try to [remove unnecessary dependencies from your Effects.](https://react.dev/learn/removing-effect-dependencies) For example, instead of memoization, it’s often simpler to move some object or a function inside an Effect or outside the component.
If a specific interaction still feels laggy, [use the React Developer Tools profiler](https://legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html) to see which components would benefit the most from memoization, and add memoization where needed. These principles make your components easier to debug and understand, so it’s good to follow them in any case. In the long term, we’re researching [doing granular memoization automatically](https://www.youtube.com/watch?v=lGEMwh32soc) to solve this once and for all.
* * *
### Updating a memoized component using state[Link for Updating a memoized component using state]()
Even when a component is memoized, it will still re-render when its own state changes. Memoization only has to do with props that are passed to the component from its parent.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { memo, useState } from 'react';
export default function MyApp() {
const [name, setName] = useState('');
const [address, setAddress] = useState('');
return (
<>
<label>
Name{': '}
<input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Address{': '}
<input value={address} onChange={e => setAddress(e.target.value)} />
</label>
<Greeting name={name} />
</>
);
}
const Greeting = memo(function Greeting({ name }) {
console.log('Greeting was rendered at', new Date().toLocaleTimeString());
const [greeting, setGreeting] = useState('Hello');
return (
<>
<h3>{greeting}{name && ', '}{name}!</h3>
<GreetingSelector value={greeting} onChange={setGreeting} />
</>
);
});
function GreetingSelector({ value, onChange }) {
return (
<>
<label>
<input
type="radio"
checked={value === 'Hello'}
onChange={e => onChange('Hello')}
/>
Regular greeting
</label>
<label>
<input
type="radio"
checked={value === 'Hello and welcome'}
onChange={e => onChange('Hello and welcome')}
/>
Enthusiastic greeting
</label>
</>
);
}
```
Show more
If you set a state variable to its current value, React will skip re-rendering your component even without `memo`. You may still see your component function being called an extra time, but the result will be discarded.
* * *
### Updating a memoized component using a context[Link for Updating a memoized component using a context]()
Even when a component is memoized, it will still re-render when a context that it’s using changes. Memoization only has to do with props that are passed to the component from its parent.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createContext, memo, useContext, useState } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() {
const [theme, setTheme] = useState('dark');
function handleClick() {
setTheme(theme === 'dark' ? 'light' : 'dark');
}
return (
<ThemeContext.Provider value={theme}>
<button onClick={handleClick}>
Switch theme
</button>
<Greeting name="Taylor" />
</ThemeContext.Provider>
);
}
const Greeting = memo(function Greeting({ name }) {
console.log("Greeting was rendered at", new Date().toLocaleTimeString());
const theme = useContext(ThemeContext);
return (
<h3 className={theme}>Hello, {name}!</h3>
);
});
```
Show more
To make your component re-render only when a *part* of some context changes, split your component in two. Read what you need from the context in the outer component, and pass it down to a memoized child as a prop.
* * *
### Minimizing props changes[Link for Minimizing props changes]()
When you use `memo`, your component re-renders whenever any prop is not *shallowly equal* to what it was previously. This means that React compares every prop in your component with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Note that `Object.is(3, 3)` is `true`, but `Object.is({}, {})` is `false`.
To get the most out of `memo`, minimize the times that the props change. For example, if the prop is an object, prevent the parent component from re-creating that object every time by using [`useMemo`:](https://react.dev/reference/react/useMemo)
```
function Page() {
const [name, setName] = useState('Taylor');
const [age, setAge] = useState(42);
const person = useMemo(
() => ({ name, age }),
[name, age]
);
return <Profile person={person} />;
}
const Profile = memo(function Profile({ person }) {
// ...
});
```
A better way to minimize props changes is to make sure the component accepts the minimum necessary information in its props. For example, it could accept individual values instead of a whole object:
```
function Page() {
const [name, setName] = useState('Taylor');
const [age, setAge] = useState(42);
return <Profile name={name} age={age} />;
}
const Profile = memo(function Profile({ name, age }) {
// ...
});
```
Even individual values can sometimes be projected to ones that change less frequently. For example, here a component accepts a boolean indicating the presence of a value rather than the value itself:
```
function GroupsLanding({ person }) {
const hasGroups = person.groups !== null;
return <CallToAction hasGroups={hasGroups} />;
}
const CallToAction = memo(function CallToAction({ hasGroups }) {
// ...
});
```
When you need to pass a function to memoized component, either declare it outside your component so that it never changes, or [`useCallback`](https://react.dev/reference/react/useCallback) to cache its definition between re-renders.
* * *
### Specifying a custom comparison function[Link for Specifying a custom comparison function]()
In rare cases it may be infeasible to minimize the props changes of a memoized component. In that case, you can provide a custom comparison function, which React will use to compare the old and new props instead of using shallow equality. This function is passed as a second argument to `memo`. It should return `true` only if the new props would result in the same output as the old props; otherwise it should return `false`.
```
const Chart = memo(function Chart({ dataPoints }) {
// ...
}, arePropsEqual);
function arePropsEqual(oldProps, newProps) {
return (
oldProps.dataPoints.length === newProps.dataPoints.length &&
oldProps.dataPoints.every((oldPoint, index) => {
const newPoint = newProps.dataPoints[index];
return oldPoint.x === newPoint.x && oldPoint.y === newPoint.y;
})
);
}
```
If you do this, use the Performance panel in your browser developer tools to make sure that your comparison function is actually faster than re-rendering the component. You might be surprised.
When you do performance measurements, make sure that React is running in the production mode.
### Pitfall
If you provide a custom `arePropsEqual` implementation, **you must compare every prop, including functions.** Functions often [close over](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) the props and state of parent components. If you return `true` when `oldProps.onClick !== newProps.onClick`, your component will keep “seeing” the props and state from a previous render inside its `onClick` handler, leading to very confusing bugs.
Avoid doing deep equality checks inside `arePropsEqual` unless you are 100% sure that the data structure you’re working with has a known limited depth. **Deep equality checks can become incredibly slow** and can freeze your app for many seconds if someone changes the data structure later.
* * *
## Troubleshooting[Link for Troubleshooting]()
### My component re-renders when a prop is an object, array, or function[Link for My component re-renders when a prop is an object, array, or function]()
React compares old and new props by shallow equality: that is, it considers whether each new prop is reference-equal to the old prop. If you create a new object or array each time the parent is re-rendered, even if the individual elements are each the same, React will still consider it to be changed. Similarly, if you create a new function when rendering the parent component, React will consider it to have changed even if the function has the same definition. To avoid this, [simplify props or memoize props in the parent component]().
[Previouslazy](https://react.dev/reference/react/lazy)
[NextstartTransition](https://react.dev/reference/react/startTransition) |
https://react.dev/reference/react-dom/hooks | [API Reference](https://react.dev/reference/react)
# Built-in React DOM Hooks[Link for this heading]()
The `react-dom` package contains Hooks that are only supported for web applications (which run in the browser DOM environment). These Hooks are not supported in non-browser environments like iOS, Android, or Windows applications. If you are looking for Hooks that are supported in web browsers *and other environments* see [the React Hooks page](https://react.dev/reference/react). This page lists all the Hooks in the `react-dom` package.
* * *
## Form Hooks[Link for Form Hooks]()
*Forms* let you create interactive controls for submitting information. To manage forms in your components, use one of these Hooks:
- [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus) allows you to make updates to the UI based on the status of the a form.
```
function Form({ action }) {
async function increment(n) {
return n + 1;
}
const [count, incrementFormAction] = useActionState(increment, 0);
return (
<form action={action}>
<button formAction={incrementFormAction}>Count: {count}</button>
<Button />
</form>
);
}
function Button() {
const { pending } = useFormStatus();
return (
<button disabled={pending} type="submit">
Submit
</button>
);
}
```
[NextuseFormStatus](https://react.dev/reference/react-dom/hooks/useFormStatus) |
https://react.dev/reference/react-dom/hooks/useFormStatus | [API Reference](https://react.dev/reference/react)
[Hooks](https://react.dev/reference/react-dom/hooks)
# useFormStatus[Link for this heading]()
`useFormStatus` is a Hook that gives you status information of the last form submission.
```
const { pending, data, method, action } = useFormStatus();
```
- [Reference]()
- [`useFormStatus()`]()
- [Usage]()
- [Display a pending state during form submission]()
- [Read the form data being submitted]()
- [Troubleshooting]()
- [`status.pending` is never `true`]()
* * *
## Reference[Link for Reference]()
### `useFormStatus()`[Link for this heading]()
The `useFormStatus` Hook provides status information of the last form submission.
```
import { useFormStatus } from "react-dom";
import action from './actions';
function Submit() {
const status = useFormStatus();
return <button disabled={status.pending}>Submit</button>
}
export default function App() {
return (
<form action={action}>
<Submit />
</form>
);
}
```
To get status information, the `Submit` component must be rendered within a `<form>`. The Hook returns information like the `pending` property which tells you if the form is actively submitting.
In the above example, `Submit` uses this information to disable `<button>` presses while the form is submitting.
[See more examples below.]()
#### Parameters[Link for Parameters]()
`useFormStatus` does not take any parameters.
#### Returns[Link for Returns]()
A `status` object with the following properties:
- `pending`: A boolean. If `true`, this means the parent `<form>` is pending submission. Otherwise, `false`.
- `data`: An object implementing the [`FormData interface`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) that contains the data the parent `<form>` is submitting. If there is no active submission or no parent `<form>`, it will be `null`.
- `method`: A string value of either `'get'` or `'post'`. This represents whether the parent `<form>` is submitting with either a `GET` or `POST` [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). By default, a `<form>` will use the `GET` method and can be specified by the [`method`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) property.
<!--THE END-->
- `action`: A reference to the function passed to the `action` prop on the parent `<form>`. If there is no parent `<form>`, the property is `null`. If there is a URI value provided to the `action` prop, or no `action` prop specified, `status.action` will be `null`.
#### Caveats[Link for Caveats]()
- The `useFormStatus` Hook must be called from a component that is rendered inside a `<form>`.
- `useFormStatus` will only return status information for a parent `<form>`. It will not return status information for any `<form>` rendered in that same component or children components.
* * *
## Usage[Link for Usage]()
### Display a pending state during form submission[Link for Display a pending state during form submission]()
To display a pending state while a form is submitting, you can call the `useFormStatus` Hook in a component rendered in a `<form>` and read the `pending` property returned.
Here, we use the `pending` property to indicate the form is submitting.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useFormStatus } from "react-dom";
import { submitForm } from "./actions.js";
function Submit() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Submitting..." : "Submit"}
</button>
);
}
function Form({ action }) {
return (
<form action={action}>
<Submit />
</form>
);
}
export default function App() {
return <Form action={submitForm} />;
}
```
Show more
### Pitfall
##### `useFormStatus` will not return status information for a `<form>` rendered in the same component.[Link for this heading]()
The `useFormStatus` Hook only returns status information for a parent `<form>` and not for any `<form>` rendered in the same component calling the Hook, or child components.
```
function Form() {
// 🚩 `pending` will never be true
// useFormStatus does not track the form rendered in this component
const { pending } = useFormStatus();
return <form action={submit}></form>;
}
```
Instead call `useFormStatus` from inside a component that is located inside `<form>`.
```
function Submit() {
// ✅ `pending` will be derived from the form that wraps the Submit component
const { pending } = useFormStatus();
return <button disabled={pending}>...</button>;
}
function Form() {
// This is the <form> `useFormStatus` tracks
return (
<form action={submit}>
<Submit />
</form>
);
}
```
### Read the form data being submitted[Link for Read the form data being submitted]()
You can use the `data` property of the status information returned from `useFormStatus` to display what data is being submitted by the user.
Here, we have a form where users can request a username. We can use `useFormStatus` to display a temporary status message confirming what username they have requested.
UsernameForm.jsApp.js
UsernameForm.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import {useState, useMemo, useRef} from 'react';
import {useFormStatus} from 'react-dom';
export default function UsernameForm() {
const {pending, data} = useFormStatus();
return (
<div>
<h3>Request a Username: </h3>
<input type="text" name="username" disabled={pending}/>
<button type="submit" disabled={pending}>
Submit
</button>
<br />
<p>{data ? `Requesting ${data?.get("username")}...`: ''}</p>
</div>
);
}
```
Show more
* * *
## Troubleshooting[Link for Troubleshooting]()
### `status.pending` is never `true`[Link for this heading]()
`useFormStatus` will only return status information for a parent `<form>`.
If the component that calls `useFormStatus` is not nested in a `<form>`, `status.pending` will always return `false`. Verify `useFormStatus` is called in a component that is a child of a `<form>` element.
`useFormStatus` will not track the status of a `<form>` rendered in the same component. See [Pitfall]() for more details.
[PreviousHooks](https://react.dev/reference/react-dom/hooks)
[NextComponents](https://react.dev/reference/react-dom/components) |
https://react.dev/reference/react-dom/components/form | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <form>[Link for this heading]()
The [built-in browser `<form>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) lets you create interactive controls for submitting information.
```
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
```
- [Reference]()
- [`<form>`]()
- [Usage]()
- [Handle form submission on the client]()
- [Handle form submission with a Server Function]()
- [Display a pending state during form submission]()
- [Optimistically updating form data]()
- [Handling form submission errors]()
- [Display a form submission error without JavaScript]()
- [Handling multiple submission types]()
* * *
## Reference[Link for Reference]()
### `<form>`[Link for this heading]()
To create interactive controls for submitting information, render the [built-in browser `<form>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
```
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
```
[See more examples below.]()
#### Props[Link for Props]()
`<form>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
[`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form): a URL or function. When a URL is passed to `action` the form will behave like the HTML form component. When a function is passed to `action` the function will handle the form submission. The function passed to `action` may be async and will be called with a single argument containing the [form data](https://developer.mozilla.org/en-US/docs/Web/API/FormData) of the submitted form. The `action` prop can be overridden by a `formAction` attribute on a `<button>`, `<input type="submit">`, or `<input type="image">` component.
#### Caveats[Link for Caveats]()
- When a function is passed to `action` or `formAction` the HTTP method will be POST regardless of value of the `method` prop.
* * *
## Usage[Link for Usage]()
### Handle form submission on the client[Link for Handle form submission on the client]()
Pass a function to the `action` prop of form to run the function when the form is submitted. [`formData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) will be passed to the function as an argument so you can access the data submitted by the form. This differs from the conventional [HTML action](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form), which only accepts URLs. After the `action` function succeeds, all uncontrolled field elements in the form are reset.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function Search() {
function search(formData) {
const query = formData.get("query");
alert(`You searched for '${query}'`);
}
return (
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}
```
### Handle form submission with a Server Function[Link for Handle form submission with a Server Function]()
Render a `<form>` with an input and submit button. Pass a Server Function (a function marked with [`'use server'`](https://react.dev/reference/rsc/use-server)) to the `action` prop of form to run the function when the form is submitted.
Passing a Server Function to `<form action>` allow users to submit forms without JavaScript enabled or before the code has loaded. This is beneficial to users who have a slow connection, device, or have JavaScript disabled and is similar to the way forms work when a URL is passed to the `action` prop.
You can use hidden form fields to provide data to the `<form>`’s action. The Server Function will be called with the hidden form field data as an instance of [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
```
import { updateCart } from './lib.js';
function AddToCart({productId}) {
async function addToCart(formData) {
'use server'
const productId = formData.get('productId')
await updateCart(productId)
}
return (
<form action={addToCart}>
<input type="hidden" name="productId" value={productId} />
<button type="submit">Add to Cart</button>
</form>
);
}
```
In lieu of using hidden form fields to provide data to the `<form>`’s action, you can call the `bind` method to supply it with extra arguments. This will bind a new argument (`productId`) to the function in addition to the `formData` that is passed as an argument to the function.
```
import { updateCart } from './lib.js';
function AddToCart({productId}) {
async function addToCart(productId, formData) {
"use server";
await updateCart(productId)
}
const addProductToCart = addToCart.bind(null, productId);
return (
<form action={addProductToCart}>
<button type="submit">Add to Cart</button>
</form>
);
}
```
When `<form>` is rendered by a [Server Component](https://react.dev/reference/rsc/use-client), and a [Server Function](https://react.dev/reference/rsc/server-functions) is passed to the `<form>`’s `action` prop, the form is [progressively enhanced](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement).
### Display a pending state during form submission[Link for Display a pending state during form submission]()
To display a pending state when a form is being submitted, you can call the `useFormStatus` Hook in a component rendered in a `<form>` and read the `pending` property returned.
Here, we use the `pending` property to indicate the form is submitting.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useFormStatus } from "react-dom";
import { submitForm } from "./actions.js";
function Submit() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Submitting..." : "Submit"}
</button>
);
}
function Form({ action }) {
return (
<form action={action}>
<Submit />
</form>
);
}
export default function App() {
return <Form action={submitForm} />;
}
```
Show more
To learn more about the `useFormStatus` Hook see the [reference documentation](https://react.dev/reference/react-dom/hooks/useFormStatus).
### Optimistically updating form data[Link for Optimistically updating form data]()
The `useOptimistic` Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server’s response to reflect the changes, the interface is immediately updated with the expected outcome.
For example, when a user types a message into the form and hits the “Send” button, the `useOptimistic` Hook allows the message to immediately appear in the list with a “Sending…” label, even before the message is actually sent to a server. This “optimistic” approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the “Sending…” label is removed.
App.jsactions.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useOptimistic, useState, useRef } from "react";
import { deliverMessage } from "./actions.js";
function Thread({ messages, sendMessage }) {
const formRef = useRef();
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
formRef.current.reset();
await sendMessage(formData);
}
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, newMessage) => [
...state,
{
text: newMessage,
sending: true
}
]
);
return (
<>
{optimisticMessages.map((message, index) => (
<div key={index}>
{message.text}
{!!message.sending && <small> (Sending...)</small>}
</div>
))}
<form action={formAction} ref={formRef}>
<input type="text" name="message" placeholder="Hello!" />
<button type="submit">Send</button>
</form>
</>
);
}
export default function App() {
const [messages, setMessages] = useState([
{ text: "Hello there!", sending: false, key: 1 }
]);
async function sendMessage(formData) {
const sentMessage = await deliverMessage(formData.get("message"));
setMessages([...messages, { text: sentMessage }]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}
```
Show more
### Handling form submission errors[Link for Handling form submission errors]()
In some cases the function called by a `<form>`’s `action` prop throws an error. You can handle these errors by wrapping `<form>` in an Error Boundary. If the function called by a `<form>`’s `action` prop throws an error, the fallback for the error boundary will be displayed.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { ErrorBoundary } from "react-error-boundary";
export default function Search() {
function search() {
throw new Error("search error");
}
return (
<ErrorBoundary
fallback={<p>There was an error while submitting the form</p>}
>
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
</ErrorBoundary>
);
}
```
Show more
### Display a form submission error without JavaScript[Link for Display a form submission error without JavaScript]()
Displaying a form submission error message before the JavaScript bundle loads for progressive enhancement requires that:
1. `<form>` be rendered by a [Server Component](https://react.dev/reference/rsc/use-client)
2. the function passed to the `<form>`’s `action` prop be a [Server Function](https://react.dev/reference/rsc/server-functions)
3. the `useActionState` Hook be used to display the error message
`useActionState` takes two parameters: a [Server Function](https://react.dev/reference/rsc/server-functions) and an initial state. `useActionState` returns two values, a state variable and an action. The action returned by `useActionState` should be passed to the `action` prop of the form. The state variable returned by `useActionState` can be used to display an error message. The value returned by the Server Function passed to `useActionState` will be used to update the state variable.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useActionState } from "react";
import { signUpNewUser } from "./api";
export default function Page() {
async function signup(prevState, formData) {
"use server";
const email = formData.get("email");
try {
await signUpNewUser(email);
alert(`Added "${email}"`);
} catch (err) {
return err.toString();
}
}
const [message, signupAction] = useActionState(signup, null);
return (
<>
<h1>Signup for my newsletter</h1>
<p>Signup with the same email twice to see an error</p>
<form action={signupAction} id="signup-form">
<label htmlFor="email">Email: </label>
<input name="email" id="email" placeholder="[email protected]" />
<button>Sign up</button>
{!!message && <p>{message}</p>}
</form>
</>
);
}
```
Show more
Learn more about updating state from a form action with the [`useActionState`](https://react.dev/reference/react/useActionState) docs
### Handling multiple submission types[Link for Handling multiple submission types]()
Forms can be designed to handle multiple submission actions based on the button pressed by the user. Each button inside a form can be associated with a distinct action or behavior by setting the `formAction` prop.
When a user taps a specific button, the form is submitted, and a corresponding action, defined by that button’s attributes and action, is executed. For instance, a form might submit an article for review by default but have a separate button with `formAction` set to save the article as a draft.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function Search() {
function publish(formData) {
const content = formData.get("content");
const button = formData.get("button");
alert(`'${content}' was published with the '${button}' button`);
}
function save(formData) {
const content = formData.get("content");
alert(`Your draft of '${content}' has been saved!`);
}
return (
<form action={publish}>
<textarea name="content" rows={4} cols={40} />
<br />
<button type="submit" name="button" value="submit">Publish</button>
<button formAction={save}>Save draft</button>
</form>
);
}
```
Show more
[PreviousCommon (e.g. <div>)](https://react.dev/reference/react-dom/components/common)
[Next<input>](https://react.dev/reference/react-dom/components/input) |
https://react.dev/reference/react-dom/components | [API Reference](https://react.dev/reference/react)
# React DOM Components[Link for this heading]()
React supports all of the browser built-in [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) and [SVG](https://developer.mozilla.org/en-US/docs/Web/SVG/Element) components.
* * *
## Common components[Link for Common components]()
All of the built-in browser components support some props and events.
- [Common components (e.g. `<div>`)](https://react.dev/reference/react-dom/components/common)
This includes React-specific props like `ref` and `dangerouslySetInnerHTML`.
* * *
## Form components[Link for Form components]()
These built-in browser components accept user input:
- [`<input>`](https://react.dev/reference/react-dom/components/input)
- [`<select>`](https://react.dev/reference/react-dom/components/select)
- [`<textarea>`](https://react.dev/reference/react-dom/components/textarea)
They are special in React because passing the `value` prop to them makes them [*controlled.*](https://react.dev/reference/react-dom/components/input)
* * *
## Resource and Metadata Components[Link for Resource and Metadata Components]()
These built-in browser components let you load external resources or annotate the document with metadata:
- [`<link>`](https://react.dev/reference/react-dom/components/link)
- [`<meta>`](https://react.dev/reference/react-dom/components/meta)
- [`<script>`](https://react.dev/reference/react-dom/components/script)
- [`<style>`](https://react.dev/reference/react-dom/components/style)
- [`<title>`](https://react.dev/reference/react-dom/components/title)
They are special in React because React can render them into the document head, suspend while resources are loading, and enact other behaviors that are described on the reference page for each specific component.
* * *
## All HTML components[Link for All HTML components]()
React supports all built-in browser HTML components. This includes:
- [`<aside>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside)
- [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio)
- [`<b>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b)
- [`<base>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base)
- [`<bdi>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/bdi)
- [`<bdo>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/bdo)
- [`<blockquote>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote)
- [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)
- [`<br>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br)
- [`<button>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button)
- [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas)
- [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption)
- [`<cite>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite)
- [`<code>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code)
- [`<col>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col)
- [`<colgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup)
- [`<data>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data)
- [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist)
- [`<dd>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd)
- [`<del>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del)
- [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details)
- [`<dfn>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dfn)
- [`<dialog>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog)
- [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div)
- [`<dl>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl)
- [`<dt>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt)
- [`<em>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em)
- [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed)
- [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset)
- [`<figcaption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption)
- [`<figure>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure)
- [`<footer>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer)
- [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
- [`<h1>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h1)
- [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
- [`<header>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header)
- [`<hgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hgroup)
- [`<hr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr)
- [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html)
- [`<i>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i)
- [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)
- [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img)
- [`<input>`](https://react.dev/reference/react-dom/components/input)
- [`<ins>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins)
- [`<kbd>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd)
- [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label)
- [`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend)
- [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li)
- [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
- [`<main>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main)
- [`<map>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map)
- [`<mark>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark)
- [`<menu>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu)
- [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
- [`<meter>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter)
- [`<nav>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav)
- [`<noscript>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript)
- [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object)
- [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol)
- [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup)
- [`<option>`](https://react.dev/reference/react-dom/components/option)
- [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output)
- [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p)
- [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture)
- [`<pre>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre)
- [`<progress>`](https://react.dev/reference/react-dom/components/progress)
- [`<q>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q)
- [`<rp>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rp)
- [`<rt>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rt)
- [`<ruby>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ruby)
- [`<s>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s)
- [`<samp>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/samp)
- [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
- [`<section>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section)
- [`<select>`](https://react.dev/reference/react-dom/components/select)
- [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot)
- [`<small>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small)
- [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source)
- [`<span>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span)
- [`<strong>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong)
- [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style)
- [`<sub>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub)
- [`<summary>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary)
- [`<sup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup)
- [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table)
- [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody)
- [`<td>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td)
- [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template)
- [`<textarea>`](https://react.dev/reference/react-dom/components/textarea)
- [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot)
- [`<th>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th)
- [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead)
- [`<time>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time)
- [`<title>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title)
- [`<tr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr)
- [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track)
- [`<u>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u)
- [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul)
- [`<var>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/var)
- [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video)
- [`<wbr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr)
### Note
Similar to the [DOM standard,](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) React uses a `camelCase` convention for prop names. For example, you’ll write `tabIndex` instead of `tabindex`. You can convert existing HTML to JSX with an [online converter.](https://transform.tools/html-to-jsx)
* * *
### Custom HTML elements[Link for Custom HTML elements]()
If you render a tag with a dash, like `<my-element>`, React will assume you want to render a [custom HTML element.](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) In React, rendering custom elements works differently from rendering built-in browser tags:
- All custom element props are serialized to strings and are always set using attributes.
- Custom elements accept `class` rather than `className`, and `for` rather than `htmlFor`.
If you render a built-in browser HTML element with an [`is`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/is) attribute, it will also be treated as a custom element.
### Note
[A future version of React will include more comprehensive support for custom elements.](https://github.com/facebook/react/issues/11347)
You can try it by upgrading React packages to the most recent experimental version:
- `react@experimental`
- `react-dom@experimental`
Experimental versions of React may contain bugs. Don’t use them in production.
* * *
## All SVG components[Link for All SVG components]()
React supports all built-in browser SVG components. This includes:
- [`<a>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/a)
- [`<animate>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animate)
- [`<animateMotion>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animateMotion)
- [`<animateTransform>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animateTransform)
- [`<circle>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/circle)
- [`<clipPath>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/clipPath)
- [`<defs>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs)
- [`<desc>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/desc)
- [`<discard>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/discard)
- [`<ellipse>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/ellipse)
- [`<feBlend>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feBlend)
- [`<feColorMatrix>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feColorMatrix)
- [`<feComponentTransfer>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feComponentTransfer)
- [`<feComposite>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feComposite)
- [`<feConvolveMatrix>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feConvolveMatrix)
- [`<feDiffuseLighting>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDiffuseLighting)
- [`<feDisplacementMap>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDisplacementMap)
- [`<feDistantLight>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDistantLight)
- [`<feDropShadow>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDropShadow)
- [`<feFlood>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFlood)
- [`<feFuncA>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncA)
- [`<feFuncB>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncB)
- [`<feFuncG>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncG)
- [`<feFuncR>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncR)
- [`<feGaussianBlur>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feGaussianBlur)
- [`<feImage>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feImage)
- [`<feMerge>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feMerge)
- [`<feMergeNode>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feMergeNode)
- [`<feMorphology>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feMorphology)
- [`<feOffset>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feOffset)
- [`<fePointLight>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/fePointLight)
- [`<feSpecularLighting>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feSpecularLighting)
- [`<feSpotLight>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feSpotLight)
- [`<feTile>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feTile)
- [`<feTurbulence>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feTurbulence)
- [`<filter>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/filter)
- [`<foreignObject>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject)
- [`<g>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g)
- `<hatch>`
- `<hatchpath>`
- [`<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image)
- [`<line>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line)
- [`<linearGradient>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient)
- [`<marker>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/marker)
- [`<mask>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/mask)
- [`<metadata>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/metadata)
- [`<mpath>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/mpath)
- [`<path>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path)
- [`<pattern>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/pattern)
- [`<polygon>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/polygon)
- [`<polyline>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/polyline)
- [`<radialGradient>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/radialGradient)
- [`<rect>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/rect)
- [`<script>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/script)
- [`<set>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/set)
- [`<stop>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/stop)
- [`<style>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/style)
- [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg)
- [`<switch>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/switch)
- [`<symbol>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/symbol)
- [`<text>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text)
- [`<textPath>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/textPath)
- [`<title>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/title)
- [`<tspan>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/tspan)
- [`<use>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use)
- [`<view>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/view)
### Note
Similar to the [DOM standard,](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) React uses a `camelCase` convention for prop names. For example, you’ll write `tabIndex` instead of `tabindex`. You can convert existing SVG to JSX with an [online converter.](https://transform.tools/)
Namespaced attributes also have to be written without the colon:
- `xlink:actuate` becomes `xlinkActuate`.
- `xlink:arcrole` becomes `xlinkArcrole`.
- `xlink:href` becomes `xlinkHref`.
- `xlink:role` becomes `xlinkRole`.
- `xlink:show` becomes `xlinkShow`.
- `xlink:title` becomes `xlinkTitle`.
- `xlink:type` becomes `xlinkType`.
- `xml:base` becomes `xmlBase`.
- `xml:lang` becomes `xmlLang`.
- `xml:space` becomes `xmlSpace`.
- `xmlns:xlink` becomes `xmlnsXlink`.
[PrevioususeFormStatus](https://react.dev/reference/react-dom/hooks/useFormStatus)
[NextCommon (e.g. <div>)](https://react.dev/reference/react-dom/components/common) |
https://react.dev/reference/react-dom/components/option | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <option>[Link for this heading]()
The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) lets you render an option inside a [`<select>`](https://react.dev/reference/react-dom/components/select) box.
```
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
- [Reference]()
- [`<option>`]()
- [Usage]()
- [Displaying a select box with options]()
* * *
## Reference[Link for Reference]()
### `<option>`[Link for this heading]()
The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) lets you render an option inside a [`<select>`](https://react.dev/reference/react-dom/components/select) box.
```
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
[See more examples below.]()
#### Props[Link for Props]()
`<option>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
Additionally, `<option>` supports these props:
- [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option): A boolean. If `true`, the option will not be selectable and will appear dimmed.
- [`label`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option): A string. Specifies the meaning of the option. If not specified, the text inside the option is used.
- [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option): The value to be used [when submitting the parent `<select>` in a form](https://react.dev/reference/react-dom/components/select) if this option is selected.
#### Caveats[Link for Caveats]()
- React does not support the `selected` attribute on `<option>`. Instead, pass this option’s `value` to the parent [`<select defaultValue>`](https://react.dev/reference/react-dom/components/select) for an uncontrolled select box, or [`<select value>`](https://react.dev/reference/react-dom/components/select) for a controlled select.
* * *
## Usage[Link for Usage]()
### Displaying a select box with options[Link for Displaying a select box with options]()
Render a `<select>` with a list of `<option>` components inside to display a select box. Give each `<option>` a `value` representing the data to be submitted with the form.
[Read more about displaying a `<select>` with a list of `<option>` components.](https://react.dev/reference/react-dom/components/select)
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function FruitPicker() {
return (
<label>
Pick a fruit:
<select name="selectedFruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</label>
);
}
```
[Previous<input>](https://react.dev/reference/react-dom/components/input)
[Next<progress>](https://react.dev/reference/react-dom/components/progress) |
https://react.dev/reference/react-dom/components/input | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <input>[Link for this heading]()
The [built-in browser `<input>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) lets you render different kinds of form inputs.
```
<input />
```
- [Reference]()
- [`<input>`]()
- [Usage]()
- [Displaying inputs of different types]()
- [Providing a label for an input]()
- [Providing an initial value for an input]()
- [Reading the input values when submitting a form]()
- [Controlling an input with a state variable]()
- [Optimizing re-rendering on every keystroke]()
- [Troubleshooting]()
- [My text input doesn’t update when I type into it]()
- [My checkbox doesn’t update when I click on it]()
- [My input caret jumps to the beginning on every keystroke]()
- [I’m getting an error: “A component is changing an uncontrolled input to be controlled”]()
* * *
## Reference[Link for Reference]()
### `<input>`[Link for this heading]()
To display an input, render the [built-in browser `<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) component.
```
<input name="myInput" />
```
[See more examples below.]()
#### Props[Link for Props]()
`<input>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
- [`formAction`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string or function. Overrides the parent `<form action>` for `type="submit"` and `type="image"`. When a URL is passed to `action` the form will behave like a standard HTML form. When a function is passed to `formAction` the function will handle the form submission. See [`<form action>`](https://react.dev/reference/react-dom/components/form).
You can [make an input controlled]() by passing one of these props:
- [`checked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement): A boolean. For a checkbox input or a radio button, controls whether it is selected.
- [`value`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement): A string. For a text input, controls its text. (For a radio button, specifies its form data.)
When you pass either of them, you must also pass an `onChange` handler that updates the passed value.
These `<input>` props are only relevant for uncontrolled inputs:
- [`defaultChecked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement): A boolean. Specifies [the initial value]() for `type="checkbox"` and `type="radio"` inputs.
- [`defaultValue`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement): A string. Specifies [the initial value]() for a text input.
These `<input>` props are relevant both for uncontrolled and controlled inputs:
- [`accept`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies which filetypes are accepted by a `type="file"` input.
- [`alt`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the alternative image text for a `type="image"` input.
- [`capture`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the media (microphone, video, or camera) captured by a `type="file"` input.
- [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies one of the possible [autocomplete behaviors.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete)
- [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A boolean. If `true`, React will focus the element on mount.
- [`dirname`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the form field name for the element’s directionality.
- [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A boolean. If `true`, the input will not be interactive and will appear dimmed.
- `children`: `<input>` does not accept children.
- [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the `id` of the `<form>` this input belongs to. If omitted, it’s the closest parent form.
- [`formAction`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Overrides the parent `<form action>` for `type="submit"` and `type="image"`.
- [`formEnctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Overrides the parent `<form enctype>` for `type="submit"` and `type="image"`.
- [`formMethod`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Overrides the parent `<form method>` for `type="submit"` and `type="image"`.
- [`formNoValidate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Overrides the parent `<form noValidate>` for `type="submit"` and `type="image"`.
- [`formTarget`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Overrides the parent `<form target>` for `type="submit"` and `type="image"`.
- [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the image height for `type="image"`.
- [`list`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the `id` of the `<datalist>` with the autocomplete options.
- [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A number. Specifies the maximum value of numerical and datetime inputs.
- [`maxLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A number. Specifies the maximum length of text and other inputs.
- [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A number. Specifies the minimum value of numerical and datetime inputs.
- [`minLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A number. Specifies the minimum length of text and other inputs.
- [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A boolean. Specifies whether multiple values are allowed for `<type="file"` and `type="email"`.
- [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the name for this input that’s [submitted with the form.]()
- `onChange`: An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Required for [controlled inputs.]() Fires immediately when the input’s value is changed by the user (for example, it fires on every keystroke). Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
- `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
- `onInputCapture`: A version of `onInput` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
- `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires after the selection inside the `<input>` changes. React extends the `onSelect` event to also fire for empty selection and on edits (which may affect the selection).
- `onSelectCapture`: A version of `onSelect` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`pattern`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the pattern that the `value` must match.
- [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Displayed in a dimmed color when the input value is empty.
- [`readOnly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A boolean. If `true`, the input is not editable by the user.
- [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A boolean. If `true`, the value must be provided for the form to submit.
- [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A number. Similar to setting width, but the unit depends on the control.
- [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the image source for a `type="image"` input.
- [`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A positive number or an `'any'` string. Specifies the distance between valid values.
- [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. One of the [input types.](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
- [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the image width for a `type="image"` input.
#### Caveats[Link for Caveats]()
- Checkboxes need `checked` (or `defaultChecked`), not `value` (or `defaultValue`).
- If a text input receives a string `value` prop, it will be [treated as controlled.]()
- If a checkbox or a radio button receives a boolean `checked` prop, it will be [treated as controlled.]()
- An input can’t be both controlled and uncontrolled at the same time.
- An input cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled input needs an `onChange` event handler that synchronously updates its backing value.
* * *
## Usage[Link for Usage]()
### Displaying inputs of different types[Link for Displaying inputs of different types]()
To display an input, render an `<input>` component. By default, it will be a text input. You can pass `type="checkbox"` for a checkbox, `type="radio"` for a radio button, [or one of the other input types.](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function MyForm() {
return (
<>
<label>
Text input: <input name="myInput" />
</label>
<hr />
<label>
Checkbox: <input type="checkbox" name="myCheckbox" />
</label>
<hr />
<p>
Radio buttons:
<label>
<input type="radio" name="myRadio" value="option1" />
Option 1
</label>
<label>
<input type="radio" name="myRadio" value="option2" />
Option 2
</label>
<label>
<input type="radio" name="myRadio" value="option3" />
Option 3
</label>
</p>
</>
);
}
```
Show more
* * *
### Providing a label for an input[Link for Providing a label for an input]()
Typically, you will place every `<input>` inside a [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) tag. This tells the browser that this label is associated with that input. When the user clicks the label, the browser will automatically focus the input. It’s also essential for accessibility: a screen reader will announce the label caption when the user focuses the associated input.
If you can’t nest `<input>` into a `<label>`, associate them by passing the same ID to `<input id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between multiple instances of one component, generate such an ID with [`useId`.](https://react.dev/reference/react/useId)
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useId } from 'react';
export default function Form() {
const ageInputId = useId();
return (
<>
<label>
Your first name:
<input name="firstName" />
</label>
<hr />
<label htmlFor={ageInputId}>Your age:</label>
<input id={ageInputId} name="age" type="number" />
</>
);
}
```
Show more
* * *
### Providing an initial value for an input[Link for Providing an initial value for an input]()
You can optionally specify the initial value for any input. Pass it as the `defaultValue` string for text inputs. Checkboxes and radio buttons should specify the initial value with the `defaultChecked` boolean instead.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function MyForm() {
return (
<>
<label>
Text input: <input name="myInput" defaultValue="Some initial value" />
</label>
<hr />
<label>
Checkbox: <input type="checkbox" name="myCheckbox" defaultChecked={true} />
</label>
<hr />
<p>
Radio buttons:
<label>
<input type="radio" name="myRadio" value="option1" />
Option 1
</label>
<label>
<input
type="radio"
name="myRadio"
value="option2"
defaultChecked={true}
/>
Option 2
</label>
<label>
<input type="radio" name="myRadio" value="option3" />
Option 3
</label>
</p>
</>
);
}
```
Show more
* * *
### Reading the input values when submitting a form[Link for Reading the input values when submitting a form]()
Add a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) around your inputs with a [`<button type="submit">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) inside. It will call your `<form onSubmit>` event handler. By default, the browser will send the form data to the current URL and refresh the page. You can override that behavior by calling `e.preventDefault()`. Read the form data with [`new FormData(e.target)`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function MyForm() {
function handleSubmit(e) {
// Prevent the browser from reloading the page
e.preventDefault();
// Read the form data
const form = e.target;
const formData = new FormData(form);
// You can pass formData as a fetch body directly:
fetch('/some-api', { method: form.method, body: formData });
// Or you can work with it as a plain object:
const formJson = Object.fromEntries(formData.entries());
console.log(formJson);
}
return (
<form method="post" onSubmit={handleSubmit}>
<label>
Text input: <input name="myInput" defaultValue="Some initial value" />
</label>
<hr />
<label>
Checkbox: <input type="checkbox" name="myCheckbox" defaultChecked={true} />
</label>
<hr />
<p>
Radio buttons:
<label><input type="radio" name="myRadio" value="option1" /> Option 1</label>
<label><input type="radio" name="myRadio" value="option2" defaultChecked={true} /> Option 2</label>
<label><input type="radio" name="myRadio" value="option3" /> Option 3</label>
</p>
<hr />
<button type="reset">Reset form</button>
<button type="submit">Submit form</button>
</form>
);
}
```
Show more
### Note
Give a `name` to every `<input>`, for example `<input name="firstName" defaultValue="Taylor" />`. The `name` you specified will be used as a key in the form data, for example `{ firstName: "Taylor" }`.
### Pitfall
By default, *any* `<button>` inside a `<form>` will submit it. This can be surprising! If you have your own custom `Button` React component, consider returning [`<button type="button">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button) instead of `<button>`. Then, to be explicit, use `<button type="submit">` for buttons that *are* supposed to submit the form.
* * *
### Controlling an input with a state variable[Link for Controlling an input with a state variable]()
An input like `<input />` is *uncontrolled.* Even if you [pass an initial value]() like `<input defaultValue="Initial text" />`, your JSX only specifies the initial value. It does not control what the value should be right now.
**To render a *controlled* input, pass the `value` prop to it (or `checked` for checkboxes and radios).** React will force the input to always have the `value` you passed. Usually, you would do this by declaring a [state variable:](https://react.dev/reference/react/useState)
```
function Form() {
const [firstName, setFirstName] = useState(''); // Declare a state variable...
// ...
return (
<input
value={firstName} // ...force the input's value to match the state variable...
onChange={e => setFirstName(e.target.value)} // ... and update the state variable on any edits!
/>
);
}
```
A controlled input makes sense if you needed state anyway—for example, to re-render your UI on every edit:
```
function Form() {
const [firstName, setFirstName] = useState('');
return (
<>
<label>
First name:
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
</label>
{firstName !== '' && <p>Your name is {firstName}.</p>}
...
```
It’s also useful if you want to offer multiple ways to adjust the input state (for example, by clicking a button):
```
function Form() {
// ...
const [age, setAge] = useState('');
const ageAsNumber = Number(age);
return (
<>
<label>
Age:
<input
value={age}
onChange={e => setAge(e.target.value)}
type="number"
/>
<button onClick={() => setAge(ageAsNumber + 10)}>
Add 10 years
</button>
```
The `value` you pass to controlled components should not be `undefined` or `null`. If you need the initial value to be empty (such as with the `firstName` field below), initialize your state variable to an empty string (`''`).
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Form() {
const [firstName, setFirstName] = useState('');
const [age, setAge] = useState('20');
const ageAsNumber = Number(age);
return (
<>
<label>
First name:
<input
value={firstName}
onChange={e => setFirstName(e.target.value)}
/>
</label>
<label>
Age:
<input
value={age}
onChange={e => setAge(e.target.value)}
type="number"
/>
<button onClick={() => setAge(ageAsNumber + 10)}>
Add 10 years
</button>
</label>
{firstName !== '' &&
<p>Your name is {firstName}.</p>
}
{ageAsNumber > 0 &&
<p>Your age is {ageAsNumber}.</p>
}
</>
);
}
```
Show more
### Pitfall
**If you pass `value` without `onChange`, it will be impossible to type into the input.** When you control an input by passing some `value` to it, you *force* it to always have the value you passed. So if you pass a state variable as a `value` but forget to update that state variable synchronously during the `onChange` event handler, React will revert the input after every keystroke back to the `value` that you specified.
* * *
### Optimizing re-rendering on every keystroke[Link for Optimizing re-rendering on every keystroke]()
When you use a controlled input, you set the state on every keystroke. If the component containing your state re-renders a large tree, this can get slow. There’s a few ways you can optimize re-rendering performance.
For example, suppose you start with a form that re-renders all page content on every keystroke:
```
function App() {
const [firstName, setFirstName] = useState('');
return (
<>
<form>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
</form>
<PageContent />
</>
);
}
```
Since `<PageContent />` doesn’t rely on the input state, you can move the input state into its own component:
```
function App() {
return (
<>
<SignupForm />
<PageContent />
</>
);
}
function SignupForm() {
const [firstName, setFirstName] = useState('');
return (
<form>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
</form>
);
}
```
This significantly improves performance because now only `SignupForm` re-renders on every keystroke.
If there is no way to avoid re-rendering (for example, if `PageContent` depends on the search input’s value), [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue) lets you keep the controlled input responsive even in the middle of a large re-render.
* * *
## Troubleshooting[Link for Troubleshooting]()
### My text input doesn’t update when I type into it[Link for My text input doesn’t update when I type into it]()
If you render an input with `value` but no `onChange`, you will see an error in the console:
```
// 🔴 Bug: controlled text input with no onChange handler
<input value={something} />
```
Console
You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
As the error message suggests, if you only wanted to [specify the *initial* value,]() pass `defaultValue` instead:
```
// ✅ Good: uncontrolled input with an initial value
<input defaultValue={something} />
```
If you want [to control this input with a state variable,]() specify an `onChange` handler:
```
// ✅ Good: controlled input with onChange
<input value={something} onChange={e => setSomething(e.target.value)} />
```
If the value is intentionally read-only, add a `readOnly` prop to suppress the error:
```
// ✅ Good: readonly controlled input without on change
<input value={something} readOnly={true} />
```
* * *
### My checkbox doesn’t update when I click on it[Link for My checkbox doesn’t update when I click on it]()
If you render a checkbox with `checked` but no `onChange`, you will see an error in the console:
```
// 🔴 Bug: controlled checkbox with no onChange handler
<input type="checkbox" checked={something} />
```
Console
You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.
As the error message suggests, if you only wanted to [specify the *initial* value,]() pass `defaultChecked` instead:
```
// ✅ Good: uncontrolled checkbox with an initial value
<input type="checkbox" defaultChecked={something} />
```
If you want [to control this checkbox with a state variable,]() specify an `onChange` handler:
```
// ✅ Good: controlled checkbox with onChange
<input type="checkbox" checked={something} onChange={e => setSomething(e.target.checked)} />
```
### Pitfall
You need to read `e.target.checked` rather than `e.target.value` for checkboxes.
If the checkbox is intentionally read-only, add a `readOnly` prop to suppress the error:
```
// ✅ Good: readonly controlled input without on change
<input type="checkbox" checked={something} readOnly={true} />
```
* * *
### My input caret jumps to the beginning on every keystroke[Link for My input caret jumps to the beginning on every keystroke]()
If you [control an input,]() you must update its state variable to the input’s value from the DOM during `onChange`.
You can’t update it to something other than `e.target.value` (or `e.target.checked` for checkboxes):
```
function handleChange(e) {
// 🔴 Bug: updating an input to something other than e.target.value
setFirstName(e.target.value.toUpperCase());
}
```
You also can’t update it asynchronously:
```
function handleChange(e) {
// 🔴 Bug: updating an input asynchronously
setTimeout(() => {
setFirstName(e.target.value);
}, 100);
}
```
To fix your code, update it synchronously to `e.target.value`:
```
function handleChange(e) {
// ✅ Updating a controlled input to e.target.value synchronously
setFirstName(e.target.value);
}
```
If this doesn’t fix the problem, it’s possible that the input gets removed and re-added from the DOM on every keystroke. This can happen if you’re accidentally [resetting state](https://react.dev/learn/preserving-and-resetting-state) on every re-render, for example if the input or one of its parents always receives a different `key` attribute, or if you nest component function definitions (which is not supported and causes the “inner” component to always be considered a different tree).
* * *
### I’m getting an error: “A component is changing an uncontrolled input to be controlled”[Link for I’m getting an error: “A component is changing an uncontrolled input to be controlled”]()
If you provide a `value` to the component, it must remain a string throughout its lifetime.
You cannot pass `value={undefined}` first and later pass `value="some string"` because React won’t know whether you want the component to be uncontrolled or controlled. A controlled component should always receive a string `value`, not `null` or `undefined`.
If your `value` is coming from an API or a state variable, it might be initialized to `null` or `undefined`. In that case, either set it to an empty string (`''`) initially, or pass `value={someValue ?? ''}` to ensure `value` is a string.
Similarly, if you pass `checked` to a checkbox, ensure it’s always a boolean.
[Previous<form>](https://react.dev/reference/react-dom/components/form)
[Next<option>](https://react.dev/reference/react-dom/components/option) |
https://react.dev/reference/react-dom/components/select | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <select>[Link for this heading]()
The [built-in browser `<select>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) lets you render a select box with options.
```
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
- [Reference]()
- [`<select>`]()
- [Usage]()
- [Displaying a select box with options]()
- [Providing a label for a select box]()
- [Providing an initially selected option]()
- [Enabling multiple selection]()
- [Reading the select box value when submitting a form]()
- [Controlling a select box with a state variable]()
* * *
## Reference[Link for Reference]()
### `<select>`[Link for this heading]()
To display a select box, render the [built-in browser `<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) component.
```
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
[See more examples below.]()
#### Props[Link for Props]()
`<select>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
You can [make a select box controlled]() by passing a `value` prop:
- `value`: A string (or an array of strings for [`multiple={true}`]()). Controls which option is selected. Every value string match the `value` of some `<option>` nested inside the `<select>`.
When you pass `value`, you must also pass an `onChange` handler that updates the passed value.
If your `<select>` is uncontrolled, you may pass the `defaultValue` prop instead:
- `defaultValue`: A string (or an array of strings for [`multiple={true}`]()). Specifies [the initially selected option.]()
These `<select>` props are relevant both for uncontrolled and controlled select boxes:
- [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A string. Specifies one of the possible [autocomplete behaviors.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete)
- [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A boolean. If `true`, React will focus the element on mount.
- `children`: `<select>` accepts [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option), [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup), and [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) components as children. You can also pass your own components as long as they eventually render one of the allowed components. If you pass your own components that eventually render `<option>` tags, each `<option>` you render must have a `value`.
- [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A boolean. If `true`, the select box will not be interactive and will appear dimmed.
- [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A string. Specifies the `id` of the `<form>` this select box belongs to. If omitted, it’s the closest parent form.
- [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A boolean. If `true`, the browser allows [multiple selection.]()
- [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A string. Specifies the name for this select box that’s [submitted with the form.]()
- `onChange`: An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Required for [controlled select boxes.]() Fires immediately when the user picks a different option. Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
- `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
- `onInputCapture`: A version of `onInput` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
- `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A boolean. If `true`, the value must be provided for the form to submit.
- [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select): A number. For `multiple={true}` selects, specifies the preferred number of initially visible items.
#### Caveats[Link for Caveats]()
- Unlike in HTML, passing a `selected` attribute to `<option>` is not supported. Instead, use [`<select defaultValue>`]() for uncontrolled select boxes and [`<select value>`]() for controlled select boxes.
- If a select box receives a `value` prop, it will be [treated as controlled.]()
- A select box can’t be both controlled and uncontrolled at the same time.
- A select box cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled select box needs an `onChange` event handler that synchronously updates its backing value.
* * *
## Usage[Link for Usage]()
### Displaying a select box with options[Link for Displaying a select box with options]()
Render a `<select>` with a list of `<option>` components inside to display a select box. Give each `<option>` a `value` representing the data to be submitted with the form.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function FruitPicker() {
return (
<label>
Pick a fruit:
<select name="selectedFruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</label>
);
}
```
* * *
### Providing a label for a select box[Link for Providing a label for a select box]()
Typically, you will place every `<select>` inside a [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) tag. This tells the browser that this label is associated with that select box. When the user clicks the label, the browser will automatically focus the select box. It’s also essential for accessibility: a screen reader will announce the label caption when the user focuses the select box.
If you can’t nest `<select>` into a `<label>`, associate them by passing the same ID to `<select id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between multiple instances of one component, generate such an ID with [`useId`.](https://react.dev/reference/react/useId)
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useId } from 'react';
export default function Form() {
const vegetableSelectId = useId();
return (
<>
<label>
Pick a fruit:
<select name="selectedFruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</label>
<hr />
<label htmlFor={vegetableSelectId}>
Pick a vegetable:
</label>
<select id={vegetableSelectId} name="selectedVegetable">
<option value="cucumber">Cucumber</option>
<option value="corn">Corn</option>
<option value="tomato">Tomato</option>
</select>
</>
);
}
```
Show more
* * *
### Providing an initially selected option[Link for Providing an initially selected option]()
By default, the browser will select the first `<option>` in the list. To select a different option by default, pass that `<option>`’s `value` as the `defaultValue` to the `<select>` element.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function FruitPicker() {
return (
<label>
Pick a fruit:
<select name="selectedFruit" defaultValue="orange">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</label>
);
}
```
### Pitfall
Unlike in HTML, passing a `selected` attribute to an individual `<option>` is not supported.
* * *
### Enabling multiple selection[Link for Enabling multiple selection]()
Pass `multiple={true}` to the `<select>` to let the user select multiple options. In that case, if you also specify `defaultValue` to choose the initially selected options, it must be an array.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function FruitPicker() {
return (
<label>
Pick some fruits:
<select
name="selectedFruit"
defaultValue={['orange', 'banana']}
multiple={true}
>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</label>
);
}
```
Show more
* * *
### Reading the select box value when submitting a form[Link for Reading the select box value when submitting a form]()
Add a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) around your select box with a [`<button type="submit">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) inside. It will call your `<form onSubmit>` event handler. By default, the browser will send the form data to the current URL and refresh the page. You can override that behavior by calling `e.preventDefault()`. Read the form data with [`new FormData(e.target)`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function EditPost() {
function handleSubmit(e) {
// Prevent the browser from reloading the page
e.preventDefault();
// Read the form data
const form = e.target;
const formData = new FormData(form);
// You can pass formData as a fetch body directly:
fetch('/some-api', { method: form.method, body: formData });
// You can generate a URL out of it, as the browser does by default:
console.log(new URLSearchParams(formData).toString());
// You can work with it as a plain object.
const formJson = Object.fromEntries(formData.entries());
console.log(formJson); // (!) This doesn't include multiple select values
// Or you can get an array of name-value pairs.
console.log([...formData.entries()]);
}
return (
<form method="post" onSubmit={handleSubmit}>
<label>
Pick your favorite fruit:
<select name="selectedFruit" defaultValue="orange">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</label>
<label>
Pick all your favorite vegetables:
<select
name="selectedVegetables"
multiple={true}
defaultValue={['corn', 'tomato']}
>
<option value="cucumber">Cucumber</option>
<option value="corn">Corn</option>
<option value="tomato">Tomato</option>
</select>
</label>
<hr />
<button type="reset">Reset</button>
<button type="submit">Submit</button>
</form>
);
}
```
Show more
### Note
Give a `name` to your `<select>`, for example `<select name="selectedFruit" />`. The `name` you specified will be used as a key in the form data, for example `{ selectedFruit: "orange" }`.
If you use `<select multiple={true}>`, the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) you’ll read from the form will include each selected value as a separate name-value pair. Look closely at the console logs in the example above.
### Pitfall
By default, *any* `<button>` inside a `<form>` will submit it. This can be surprising! If you have your own custom `Button` React component, consider returning [`<button type="button">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button) instead of `<button>`. Then, to be explicit, use `<button type="submit">` for buttons that *are* supposed to submit the form.
* * *
### Controlling a select box with a state variable[Link for Controlling a select box with a state variable]()
A select box like `<select />` is *uncontrolled.* Even if you [pass an initially selected value]() like `<select defaultValue="orange" />`, your JSX only specifies the initial value, not the value right now.
**To render a *controlled* select box, pass the `value` prop to it.** React will force the select box to always have the `value` you passed. Typically, you will control a select box by declaring a [state variable:](https://react.dev/reference/react/useState)
```
function FruitPicker() {
const [selectedFruit, setSelectedFruit] = useState('orange'); // Declare a state variable...
// ...
return (
<select
value={selectedFruit} // ...force the select's value to match the state variable...
onChange={e => setSelectedFruit(e.target.value)} // ... and update the state variable on any change!
>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
);
}
```
This is useful if you want to re-render some part of the UI in response to every selection.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function FruitPicker() {
const [selectedFruit, setSelectedFruit] = useState('orange');
const [selectedVegs, setSelectedVegs] = useState(['corn', 'tomato']);
return (
<>
<label>
Pick a fruit:
<select
value={selectedFruit}
onChange={e => setSelectedFruit(e.target.value)}
>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</label>
<hr />
<label>
Pick all your favorite vegetables:
<select
multiple={true}
value={selectedVegs}
onChange={e => {
const options = [...e.target.selectedOptions];
const values = options.map(option => option.value);
setSelectedVegs(values);
}}
>
<option value="cucumber">Cucumber</option>
<option value="corn">Corn</option>
<option value="tomato">Tomato</option>
</select>
</label>
<hr />
<p>Your favorite fruit: {selectedFruit}</p>
<p>Your favorite vegetables: {selectedVegs.join(', ')}</p>
</>
);
}
```
Show more
### Pitfall
**If you pass `value` without `onChange`, it will be impossible to select an option.** When you control a select box by passing some `value` to it, you *force* it to always have the value you passed. So if you pass a state variable as a `value` but forget to update that state variable synchronously during the `onChange` event handler, React will revert the select box after every keystroke back to the `value` that you specified.
Unlike in HTML, passing a `selected` attribute to an individual `<option>` is not supported.
[Previous<progress>](https://react.dev/reference/react-dom/components/progress)
[Next<textarea>](https://react.dev/reference/react-dom/components/textarea) |
https://react.dev/reference/react-dom/components/textarea | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <textarea>[Link for this heading]()
The [built-in browser `<textarea>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) lets you render a multiline text input.
```
<textarea />
```
- [Reference]()
- [`<textarea>`]()
- [Usage]()
- [Displaying a text area]()
- [Providing a label for a text area]()
- [Providing an initial value for a text area]()
- [Reading the text area value when submitting a form]()
- [Controlling a text area with a state variable]()
- [Troubleshooting]()
- [My text area doesn’t update when I type into it]()
- [My text area caret jumps to the beginning on every keystroke]()
- [I’m getting an error: “A component is changing an uncontrolled input to be controlled”]()
* * *
## Reference[Link for Reference]()
### `<textarea>`[Link for this heading]()
To display a text area, render the [built-in browser `<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) component.
```
<textarea name="postContent" />
```
[See more examples below.]()
#### Props[Link for Props]()
`<textarea>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
You can [make a text area controlled]() by passing a `value` prop:
- `value`: A string. Controls the text inside the text area.
When you pass `value`, you must also pass an `onChange` handler that updates the passed value.
If your `<textarea>` is uncontrolled, you may pass the `defaultValue` prop instead:
- `defaultValue`: A string. Specifies [the initial value]() for a text area.
These `<textarea>` props are relevant both for uncontrolled and controlled text areas:
- [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): Either `'on'` or `'off'`. Specifies the autocomplete behavior.
- [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A boolean. If `true`, React will focus the element on mount.
- `children`: `<textarea>` does not accept children. To set the initial value, use `defaultValue`.
- [`cols`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A number. Specifies the default width in average character widths. Defaults to `20`.
- [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A boolean. If `true`, the input will not be interactive and will appear dimmed.
- [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A string. Specifies the `id` of the `<form>` this input belongs to. If omitted, it’s the closest parent form.
- [`maxLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A number. Specifies the maximum length of text.
- [`minLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A number. Specifies the minimum length of text.
- [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input): A string. Specifies the name for this input that’s [submitted with the form.]()
- `onChange`: An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Required for [controlled text areas.]() Fires immediately when the input’s value is changed by the user (for example, it fires on every keystroke). Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
- `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
- `onInputCapture`: A version of `onInput` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
- `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement/select_event): An [`Event` handler](https://react.dev/reference/react-dom/components/common) function. Fires after the selection inside the `<textarea>` changes. React extends the `onSelect` event to also fire for empty selection and on edits (which may affect the selection).
- `onSelectCapture`: A version of `onSelect` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A string. Displayed in a dimmed color when the text area value is empty.
- [`readOnly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A boolean. If `true`, the text area is not editable by the user.
- [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A boolean. If `true`, the value must be provided for the form to submit.
- [`rows`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): A number. Specifies the default height in average character heights. Defaults to `2`.
- [`wrap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): Either `'hard'`, `'soft'`, or `'off'`. Specifies how the text should be wrapped when submitting a form.
#### Caveats[Link for Caveats]()
- Passing children like `<textarea>something</textarea>` is not allowed. [Use `defaultValue` for initial content.]()
- If a text area receives a string `value` prop, it will be [treated as controlled.]()
- A text area can’t be both controlled and uncontrolled at the same time.
- A text area cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled text area needs an `onChange` event handler that synchronously updates its backing value.
* * *
## Usage[Link for Usage]()
### Displaying a text area[Link for Displaying a text area]()
Render `<textarea>` to display a text area. You can specify its default size with the [`rows`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) and [`cols`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) attributes, but by default the user will be able to resize it. To disable resizing, you can specify `resize: none` in the CSS.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function NewPost() {
return (
<label>
Write your post:
<textarea name="postContent" rows={4} cols={40} />
</label>
);
}
```
* * *
### Providing a label for a text area[Link for Providing a label for a text area]()
Typically, you will place every `<textarea>` inside a [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) tag. This tells the browser that this label is associated with that text area. When the user clicks the label, the browser will focus the text area. It’s also essential for accessibility: a screen reader will announce the label caption when the user focuses the text area.
If you can’t nest `<textarea>` into a `<label>`, associate them by passing the same ID to `<textarea id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between instances of one component, generate such an ID with [`useId`.](https://react.dev/reference/react/useId)
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useId } from 'react';
export default function Form() {
const postTextAreaId = useId();
return (
<>
<label htmlFor={postTextAreaId}>
Write your post:
</label>
<textarea
id={postTextAreaId}
name="postContent"
rows={4}
cols={40}
/>
</>
);
}
```
Show more
* * *
### Providing an initial value for a text area[Link for Providing an initial value for a text area]()
You can optionally specify the initial value for the text area. Pass it as the `defaultValue` string.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function EditPost() {
return (
<label>
Edit your post:
<textarea
name="postContent"
defaultValue="I really enjoyed biking yesterday!"
rows={4}
cols={40}
/>
</label>
);
}
```
### Pitfall
Unlike in HTML, passing initial text like `<textarea>Some content</textarea>` is not supported.
* * *
### Reading the text area value when submitting a form[Link for Reading the text area value when submitting a form]()
Add a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) around your textarea with a [`<button type="submit">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) inside. It will call your `<form onSubmit>` event handler. By default, the browser will send the form data to the current URL and refresh the page. You can override that behavior by calling `e.preventDefault()`. Read the form data with [`new FormData(e.target)`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function EditPost() {
function handleSubmit(e) {
// Prevent the browser from reloading the page
e.preventDefault();
// Read the form data
const form = e.target;
const formData = new FormData(form);
// You can pass formData as a fetch body directly:
fetch('/some-api', { method: form.method, body: formData });
// Or you can work with it as a plain object:
const formJson = Object.fromEntries(formData.entries());
console.log(formJson);
}
return (
<form method="post" onSubmit={handleSubmit}>
<label>
Post title: <input name="postTitle" defaultValue="Biking" />
</label>
<label>
Edit your post:
<textarea
name="postContent"
defaultValue="I really enjoyed biking yesterday!"
rows={4}
cols={40}
/>
</label>
<hr />
<button type="reset">Reset edits</button>
<button type="submit">Save post</button>
</form>
);
}
```
Show more
### Note
Give a `name` to your `<textarea>`, for example `<textarea name="postContent" />`. The `name` you specified will be used as a key in the form data, for example `{ postContent: "Your post" }`.
### Pitfall
By default, *any* `<button>` inside a `<form>` will submit it. This can be surprising! If you have your own custom `Button` React component, consider returning [`<button type="button">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button) instead of `<button>`. Then, to be explicit, use `<button type="submit">` for buttons that *are* supposed to submit the form.
* * *
### Controlling a text area with a state variable[Link for Controlling a text area with a state variable]()
A text area like `<textarea />` is *uncontrolled.* Even if you [pass an initial value]() like `<textarea defaultValue="Initial text" />`, your JSX only specifies the initial value, not the value right now.
**To render a *controlled* text area, pass the `value` prop to it.** React will force the text area to always have the `value` you passed. Typically, you will control a text area by declaring a [state variable:](https://react.dev/reference/react/useState)
```
function NewPost() {
const [postContent, setPostContent] = useState(''); // Declare a state variable...
// ...
return (
<textarea
value={postContent} // ...force the input's value to match the state variable...
onChange={e => setPostContent(e.target.value)} // ... and update the state variable on any edits!
/>
);
}
```
This is useful if you want to re-render some part of the UI in response to every keystroke.
package.jsonApp.jsMarkdownPreview.js
package.json
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
{
"dependencies": {
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest",
"remarkable": "2.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {}
}
```
### Pitfall
**If you pass `value` without `onChange`, it will be impossible to type into the text area.** When you control a text area by passing some `value` to it, you *force* it to always have the value you passed. So if you pass a state variable as a `value` but forget to update that state variable synchronously during the `onChange` event handler, React will revert the text area after every keystroke back to the `value` that you specified.
* * *
## Troubleshooting[Link for Troubleshooting]()
### My text area doesn’t update when I type into it[Link for My text area doesn’t update when I type into it]()
If you render a text area with `value` but no `onChange`, you will see an error in the console:
```
// 🔴 Bug: controlled text area with no onChange handler
<textarea value={something} />
```
Console
You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
As the error message suggests, if you only wanted to [specify the *initial* value,]() pass `defaultValue` instead:
```
// ✅ Good: uncontrolled text area with an initial value
<textarea defaultValue={something} />
```
If you want [to control this text area with a state variable,]() specify an `onChange` handler:
```
// ✅ Good: controlled text area with onChange
<textarea value={something} onChange={e => setSomething(e.target.value)} />
```
If the value is intentionally read-only, add a `readOnly` prop to suppress the error:
```
// ✅ Good: readonly controlled text area without on change
<textarea value={something} readOnly={true} />
```
* * *
### My text area caret jumps to the beginning on every keystroke[Link for My text area caret jumps to the beginning on every keystroke]()
If you [control a text area,]() you must update its state variable to the text area’s value from the DOM during `onChange`.
You can’t update it to something other than `e.target.value`:
```
function handleChange(e) {
// 🔴 Bug: updating an input to something other than e.target.value
setFirstName(e.target.value.toUpperCase());
}
```
You also can’t update it asynchronously:
```
function handleChange(e) {
// 🔴 Bug: updating an input asynchronously
setTimeout(() => {
setFirstName(e.target.value);
}, 100);
}
```
To fix your code, update it synchronously to `e.target.value`:
```
function handleChange(e) {
// ✅ Updating a controlled input to e.target.value synchronously
setFirstName(e.target.value);
}
```
If this doesn’t fix the problem, it’s possible that the text area gets removed and re-added from the DOM on every keystroke. This can happen if you’re accidentally [resetting state](https://react.dev/learn/preserving-and-resetting-state) on every re-render. For example, this can happen if the text area or one of its parents always receives a different `key` attribute, or if you nest component definitions (which is not allowed in React and causes the “inner” component to remount on every render).
* * *
### I’m getting an error: “A component is changing an uncontrolled input to be controlled”[Link for I’m getting an error: “A component is changing an uncontrolled input to be controlled”]()
If you provide a `value` to the component, it must remain a string throughout its lifetime.
You cannot pass `value={undefined}` first and later pass `value="some string"` because React won’t know whether you want the component to be uncontrolled or controlled. A controlled component should always receive a string `value`, not `null` or `undefined`.
If your `value` is coming from an API or a state variable, it might be initialized to `null` or `undefined`. In that case, either set it to an empty string (`''`) initially, or pass `value={someValue ?? ''}` to ensure `value` is a string.
[Previous<select>](https://react.dev/reference/react-dom/components/select)
[Next<link>](https://react.dev/reference/react-dom/components/link) |
https://react.dev/reference/react-dom/components/common | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# Common components (e.g. <div>)[Link for this heading]()
All built-in browser components, such as [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div), support some common props and events.
- [Reference]()
- [Common components (e.g. `<div>`)]()
- [`ref` callback function]()
- [React event object]()
- [`AnimationEvent` handler function]()
- [`ClipboardEvent` handler function]()
- [`CompositionEvent` handler function]()
- [`DragEvent` handler function]()
- [`FocusEvent` handler function]()
- [`Event` handler function]()
- [`InputEvent` handler function]()
- [`KeyboardEvent` handler function]()
- [`MouseEvent` handler function]()
- [`PointerEvent` handler function]()
- [`TouchEvent` handler function]()
- [`TransitionEvent` handler function]()
- [`UIEvent` handler function]()
- [`WheelEvent` handler function]()
- [Usage]()
- [Applying CSS styles]()
- [Manipulating a DOM node with a ref]()
- [Dangerously setting the inner HTML]()
- [Handling mouse events]()
- [Handling pointer events]()
- [Handling focus events]()
- [Handling keyboard events]()
* * *
## Reference[Link for Reference]()
### Common components (e.g. `<div>`)[Link for this heading]()
```
<div className="wrapper">Some content</div>
```
[See more examples below.]()
#### Props[Link for Props]()
These special React props are supported for all built-in components:
- `children`: A React node (an element, a string, a number, [a portal,](https://react.dev/reference/react-dom/createPortal) an empty node like `null`, `undefined` and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify the `children` prop implicitly by nesting tags like `<div><span /></div>`.
- `dangerouslySetInnerHTML`: An object of the form `{ __html: '<p>some html</p>' }` with a raw HTML string inside. Overrides the [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn’t trusted (for example, if it’s based on user data), you risk introducing an [XSS](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerability. [Read more about using `dangerouslySetInnerHTML`.]()
- `ref`: A ref object from [`useRef`](https://react.dev/reference/react/useRef) or [`createRef`](https://react.dev/reference/react/createRef), or a [`ref` callback function,]() or a string for [legacy refs.](https://reactjs.org/docs/refs-and-the-dom.html) Your ref will be filled with the DOM element for this node. [Read more about manipulating the DOM with refs.]()
- `suppressContentEditableWarning`: A boolean. If `true`, suppresses the warning that React shows for elements that both have `children` and `contentEditable={true}` (which normally do not work together). Use this if you’re building a text input library that manages the `contentEditable` content manually.
- `suppressHydrationWarning`: A boolean. If you use [server rendering,](https://react.dev/reference/react-dom/server) normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you set `suppressHydrationWarning` to `true`, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don’t overuse it. [Read about suppressing hydration errors.](https://react.dev/reference/react-dom/client/hydrateRoot)
- `style`: An object with CSS styles, for example `{ fontWeight: 'bold', margin: 20 }`. Similarly to the DOM [`style`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) property, the CSS property names need to be written as `camelCase`, for example `fontWeight` instead of `font-weight`. You can pass strings or numbers as values. If you pass a number, like `width: 100`, React will automatically append `px` (“pixels”) to the value unless it’s a [unitless property.](https://github.com/facebook/react/blob/81d4ee9ca5c405dce62f64e61506b8e155f38d8d/packages/react-dom-bindings/src/shared/CSSProperty.js) We recommend using `style` only for dynamic styles where you don’t know the style values ahead of time. In other cases, applying plain CSS classes with `className` is more efficient. [Read more about `className` and `style`.]()
These standard DOM props are also supported for all built-in components:
- [`accessKey`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/accesskey): A string. Specifies a keyboard shortcut for the element. [Not generally recommended.](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/accesskey)
- [`aria-*`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes): ARIA attributes let you specify the accessibility tree information for this element. See [ARIA attributes](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes) for a complete reference. In React, all ARIA attribute names are exactly the same as in HTML.
- [`autoCapitalize`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize): A string. Specifies whether and how the user input should be capitalized.
- [`className`](https://developer.mozilla.org/en-US/docs/Web/API/Element/className): A string. Specifies the element’s CSS class name. [Read more about applying CSS styles.]()
- [`contentEditable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable): A boolean. If `true`, the browser lets the user edit the rendered element directly. This is used to implement rich text input libraries like [Lexical.](https://lexical.dev/) React warns if you try to pass React children to an element with `contentEditable={true}` because React will not be able to update its content after user edits.
- [`data-*`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*): Data attributes let you attach some string data to the element, for example `data-fruit="banana"`. In React, they are not commonly used because you would usually read data from props or state instead.
- [`dir`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir): Either `'ltr'` or `'rtl'`. Specifies the text direction of the element.
- [`draggable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable): A boolean. Specifies whether the element is draggable. Part of [HTML Drag and Drop API.](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API)
- [`enterKeyHint`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/enterKeyHint): A string. Specifies which action to present for the enter key on virtual keyboards.
- [`htmlFor`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor): A string. For [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) and [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output), lets you [associate the label with some control.](https://react.dev/reference/react-dom/components/input) Same as [`for` HTML attribute.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/for) React uses the standard DOM property names (`htmlFor`) instead of HTML attribute names.
- [`hidden`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden): A boolean or a string. Specifies whether the element should be hidden.
- [`id`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id): A string. Specifies a unique identifier for this element, which can be used to find it later or connect it with other elements. Generate it with [`useId`](https://react.dev/reference/react/useId) to avoid clashes between multiple instances of the same component.
- [`is`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/is): A string. If specified, the component will behave like a [custom element.](https://react.dev/reference/react-dom/components)
- [`inputMode`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode): A string. Specifies what kind of keyboard to display (for example, text, number or telephone).
- [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop): A string. Specifies which property the element represents for structured data crawlers.
- [`lang`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang): A string. Specifies the language of the element.
- [`onAnimationEnd`](https://developer.mozilla.org/en-US/docs/Web/API/Element/animationend_event): An [`AnimationEvent` handler]() function. Fires when a CSS animation completes.
- `onAnimationEndCapture`: A version of `onAnimationEnd` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onAnimationIteration`](https://developer.mozilla.org/en-US/docs/Web/API/Element/animationiteration_event): An [`AnimationEvent` handler]() function. Fires when an iteration of a CSS animation ends, and another one begins.
- `onAnimationIterationCapture`: A version of `onAnimationIteration` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onAnimationStart`](https://developer.mozilla.org/en-US/docs/Web/API/Element/animationstart_event): An [`AnimationEvent` handler]() function. Fires when a CSS animation starts.
- `onAnimationStartCapture`: `onAnimationStart`, but fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onAuxClick`](https://developer.mozilla.org/en-US/docs/Web/API/Element/auxclick_event): A [`MouseEvent` handler]() function. Fires when a non-primary pointer button was clicked.
- `onAuxClickCapture`: A version of `onAuxClick` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- `onBeforeInput`: An [`InputEvent` handler]() function. Fires before the value of an editable element is modified. React does *not* yet use the native [`beforeinput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/beforeinput_event) event, and instead attempts to polyfill it using other events.
- `onBeforeInputCapture`: A version of `onBeforeInput` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- `onBlur`: A [`FocusEvent` handler]() function. Fires when an element lost focus. Unlike the built-in browser [`blur`](https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event) event, in React the `onBlur` event bubbles.
- `onBlurCapture`: A version of `onBlur` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onClick`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event): A [`MouseEvent` handler]() function. Fires when the primary button was clicked on the pointing device.
- `onClickCapture`: A version of `onClick` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onCompositionStart`](https://developer.mozilla.org/en-US/docs/Web/API/Element/compositionstart_event): A [`CompositionEvent` handler]() function. Fires when an [input method editor](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor) starts a new composition session.
- `onCompositionStartCapture`: A version of `onCompositionStart` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onCompositionEnd`](https://developer.mozilla.org/en-US/docs/Web/API/Element/compositionend_event): A [`CompositionEvent` handler]() function. Fires when an [input method editor](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor) completes or cancels a composition session.
- `onCompositionEndCapture`: A version of `onCompositionEnd` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onCompositionUpdate`](https://developer.mozilla.org/en-US/docs/Web/API/Element/compositionupdate_event): A [`CompositionEvent` handler]() function. Fires when an [input method editor](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor) receives a new character.
- `onCompositionUpdateCapture`: A version of `onCompositionUpdate` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onContextMenu`](https://developer.mozilla.org/en-US/docs/Web/API/Element/contextmenu_event): A [`MouseEvent` handler]() function. Fires when the user tries to open a context menu.
- `onContextMenuCapture`: A version of `onContextMenu` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onCopy`](https://developer.mozilla.org/en-US/docs/Web/API/Element/copy_event): A [`ClipboardEvent` handler]() function. Fires when the user tries to copy something into the clipboard.
- `onCopyCapture`: A version of `onCopy` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onCut`](https://developer.mozilla.org/en-US/docs/Web/API/Element/cut_event): A [`ClipboardEvent` handler]() function. Fires when the user tries to cut something into the clipboard.
- `onCutCapture`: A version of `onCut` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- `onDoubleClick`: A [`MouseEvent` handler]() function. Fires when the user clicks twice. Corresponds to the browser [`dblclick` event.](https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event)
- `onDoubleClickCapture`: A version of `onDoubleClick` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onDrag`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/drag_event): A [`DragEvent` handler]() function. Fires while the user is dragging something.
- `onDragCapture`: A version of `onDrag` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onDragEnd`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragend_event): A [`DragEvent` handler]() function. Fires when the user stops dragging something.
- `onDragEndCapture`: A version of `onDragEnd` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onDragEnter`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragenter_event): A [`DragEvent` handler]() function. Fires when the dragged content enters a valid drop target.
- `onDragEnterCapture`: A version of `onDragEnter` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onDragOver`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragover_event): A [`DragEvent` handler]() function. Fires on a valid drop target while the dragged content is dragged over it. You must call `e.preventDefault()` here to allow dropping.
- `onDragOverCapture`: A version of `onDragOver` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onDragStart`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragstart_event): A [`DragEvent` handler]() function. Fires when the user starts dragging an element.
- `onDragStartCapture`: A version of `onDragStart` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onDrop`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/drop_event): A [`DragEvent` handler]() function. Fires when something is dropped on a valid drop target.
- `onDropCapture`: A version of `onDrop` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- `onFocus`: A [`FocusEvent` handler]() function. Fires when an element receives focus. Unlike the built-in browser [`focus`](https://developer.mozilla.org/en-US/docs/Web/API/Element/focus_event) event, in React the `onFocus` event bubbles.
- `onFocusCapture`: A version of `onFocus` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onGotPointerCapture`](https://developer.mozilla.org/en-US/docs/Web/API/Element/gotpointercapture_event): A [`PointerEvent` handler]() function. Fires when an element programmatically captures a pointer.
- `onGotPointerCaptureCapture`: A version of `onGotPointerCapture` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onKeyDown`](https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event): A [`KeyboardEvent` handler]() function. Fires when a key is pressed.
- `onKeyDownCapture`: A version of `onKeyDown` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onKeyPress`](https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event): A [`KeyboardEvent` handler]() function. Deprecated. Use `onKeyDown` or `onBeforeInput` instead.
- `onKeyPressCapture`: A version of `onKeyPress` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onKeyUp`](https://developer.mozilla.org/en-US/docs/Web/API/Element/keyup_event): A [`KeyboardEvent` handler]() function. Fires when a key is released.
- `onKeyUpCapture`: A version of `onKeyUp` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onLostPointerCapture`](https://developer.mozilla.org/en-US/docs/Web/API/Element/lostpointercapture_event): A [`PointerEvent` handler]() function. Fires when an element stops capturing a pointer.
- `onLostPointerCaptureCapture`: A version of `onLostPointerCapture` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onMouseDown`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mousedown_event): A [`MouseEvent` handler]() function. Fires when the pointer is pressed down.
- `onMouseDownCapture`: A version of `onMouseDown` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onMouseEnter`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event): A [`MouseEvent` handler]() function. Fires when the pointer moves inside an element. Does not have a capture phase. Instead, `onMouseLeave` and `onMouseEnter` propagate from the element being left to the one being entered.
- [`onMouseLeave`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseleave_event): A [`MouseEvent` handler]() function. Fires when the pointer moves outside an element. Does not have a capture phase. Instead, `onMouseLeave` and `onMouseEnter` propagate from the element being left to the one being entered.
- [`onMouseMove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event): A [`MouseEvent` handler]() function. Fires when the pointer changes coordinates.
- `onMouseMoveCapture`: A version of `onMouseMove` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onMouseOut`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseout_event): A [`MouseEvent` handler]() function. Fires when the pointer moves outside an element, or if it moves into a child element.
- `onMouseOutCapture`: A version of `onMouseOut` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onMouseUp`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseup_event): A [`MouseEvent` handler]() function. Fires when the pointer is released.
- `onMouseUpCapture`: A version of `onMouseUp` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPointerCancel`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointercancel_event): A [`PointerEvent` handler]() function. Fires when the browser cancels a pointer interaction.
- `onPointerCancelCapture`: A version of `onPointerCancel` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPointerDown`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerdown_event): A [`PointerEvent` handler]() function. Fires when a pointer becomes active.
- `onPointerDownCapture`: A version of `onPointerDown` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPointerEnter`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerenter_event): A [`PointerEvent` handler]() function. Fires when a pointer moves inside an element. Does not have a capture phase. Instead, `onPointerLeave` and `onPointerEnter` propagate from the element being left to the one being entered.
- [`onPointerLeave`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerleave_event): A [`PointerEvent` handler]() function. Fires when a pointer moves outside an element. Does not have a capture phase. Instead, `onPointerLeave` and `onPointerEnter` propagate from the element being left to the one being entered.
- [`onPointerMove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointermove_event): A [`PointerEvent` handler]() function. Fires when a pointer changes coordinates.
- `onPointerMoveCapture`: A version of `onPointerMove` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPointerOut`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerout_event): A [`PointerEvent` handler]() function. Fires when a pointer moves outside an element, if the pointer interaction is cancelled, and [a few other reasons.](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerout_event)
- `onPointerOutCapture`: A version of `onPointerOut` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPointerUp`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerup_event): A [`PointerEvent` handler]() function. Fires when a pointer is no longer active.
- `onPointerUpCapture`: A version of `onPointerUp` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPaste`](https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event): A [`ClipboardEvent` handler]() function. Fires when the user tries to paste something from the clipboard.
- `onPasteCapture`: A version of `onPaste` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onScroll`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scroll_event): An [`Event` handler]() function. Fires when an element has been scrolled. This event does not bubble.
- `onScrollCapture`: A version of `onScroll` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event): An [`Event` handler]() function. Fires after the selection inside an editable element like an input changes. React extends the `onSelect` event to work for `contentEditable={true}` elements as well. In addition, React extends it to fire for empty selection and on edits (which may affect the selection).
- `onSelectCapture`: A version of `onSelect` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onTouchCancel`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchcancel_event): A [`TouchEvent` handler]() function. Fires when the browser cancels a touch interaction.
- `onTouchCancelCapture`: A version of `onTouchCancel` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onTouchEnd`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchend_event): A [`TouchEvent` handler]() function. Fires when one or more touch points are removed.
- `onTouchEndCapture`: A version of `onTouchEnd` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onTouchMove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchmove_event): A [`TouchEvent` handler]() function. Fires one or more touch points are moved.
- `onTouchMoveCapture`: A version of `onTouchMove` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onTouchStart`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event): A [`TouchEvent` handler]() function. Fires when one or more touch points are placed.
- `onTouchStartCapture`: A version of `onTouchStart` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onTransitionEnd`](https://developer.mozilla.org/en-US/docs/Web/API/Element/transitionend_event): A [`TransitionEvent` handler]() function. Fires when a CSS transition completes.
- `onTransitionEndCapture`: A version of `onTransitionEnd` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onWheel`](https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event): A [`WheelEvent` handler]() function. Fires when the user rotates a wheel button.
- `onWheelCapture`: A version of `onWheel` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`role`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles): A string. Specifies the element role explicitly for assistive technologies.
- [`slot`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles): A string. Specifies the slot name when using shadow DOM. In React, an equivalent pattern is typically achieved by passing JSX as props, for example `<Layout left={<Sidebar />} right={<Content />} />`.
- [`spellCheck`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/spellcheck): A boolean or null. If explicitly set to `true` or `false`, enables or disables spellchecking.
- [`tabIndex`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex): A number. Overrides the default Tab button behavior. [Avoid using values other than `-1` and `0`.](https://www.tpgi.com/using-the-tabindex-attribute/)
- [`title`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/title): A string. Specifies the tooltip text for the element.
- [`translate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/translate): Either `'yes'` or `'no'`. Passing `'no'` excludes the element content from being translated.
You can also pass custom attributes as props, for example `mycustomprop="someValue"`. This can be useful when integrating with third-party libraries. The custom attribute name must be lowercase and must not start with `on`. The value will be converted to a string. If you pass `null` or `undefined`, the custom attribute will be removed.
These events fire only for the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) elements:
- [`onReset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset_event): An [`Event` handler]() function. Fires when a form gets reset.
- `onResetCapture`: A version of `onReset` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onSubmit`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event): An [`Event` handler]() function. Fires when a form gets submitted.
- `onSubmitCapture`: A version of `onSubmit` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
These events fire only for the [`<dialog>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog) elements. Unlike browser events, they bubble in React:
- [`onCancel`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/cancel_event): An [`Event` handler]() function. Fires when the user tries to dismiss the dialog.
- `onCancelCapture`: A version of `onCancel` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onClose`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/close_event): An [`Event` handler]() function. Fires when a dialog has been closed.
- `onCloseCapture`: A version of `onClose` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
These events fire only for the [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) elements. Unlike browser events, they bubble in React:
- [`onToggle`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDetailsElement/toggle_event): An [`Event` handler]() function. Fires when the user toggles the details.
- `onToggleCapture`: A version of `onToggle` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
These events fire for [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img), [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe), [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object), [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed), [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link), and [SVG `<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/SVG_Image_Tag) elements. Unlike browser events, they bubble in React:
- `onLoad`: An [`Event` handler]() function. Fires when the resource has loaded.
- `onLoadCapture`: A version of `onLoad` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onError`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error_event): An [`Event` handler]() function. Fires when the resource could not be loaded.
- `onErrorCapture`: A version of `onError` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
These events fire for resources like [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video). Unlike browser events, they bubble in React:
- [`onAbort`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/abort_event): An [`Event` handler]() function. Fires when the resource has not fully loaded, but not due to an error.
- `onAbortCapture`: A version of `onAbort` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onCanPlay`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplay_event): An [`Event` handler]() function. Fires when there’s enough data to start playing, but not enough to play to the end without buffering.
- `onCanPlayCapture`: A version of `onCanPlay` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onCanPlayThrough`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event): An [`Event` handler]() function. Fires when there’s enough data that it’s likely possible to start playing without buffering until the end.
- `onCanPlayThroughCapture`: A version of `onCanPlayThrough` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onDurationChange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/durationchange_event): An [`Event` handler]() function. Fires when the media duration has updated.
- `onDurationChangeCapture`: A version of `onDurationChange` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onEmptied`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/emptied_event): An [`Event` handler]() function. Fires when the media has become empty.
- `onEmptiedCapture`: A version of `onEmptied` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onEncrypted`](https://w3c.github.io/encrypted-media/): An [`Event` handler]() function. Fires when the browser encounters encrypted media.
- `onEncryptedCapture`: A version of `onEncrypted` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onEnded`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended_event): An [`Event` handler]() function. Fires when the playback stops because there’s nothing left to play.
- `onEndedCapture`: A version of `onEnded` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onError`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error_event): An [`Event` handler]() function. Fires when the resource could not be loaded.
- `onErrorCapture`: A version of `onError` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onLoadedData`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadeddata_event): An [`Event` handler]() function. Fires when the current playback frame has loaded.
- `onLoadedDataCapture`: A version of `onLoadedData` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onLoadedMetadata`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadedmetadata_event): An [`Event` handler]() function. Fires when metadata has loaded.
- `onLoadedMetadataCapture`: A version of `onLoadedMetadata` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onLoadStart`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadstart_event): An [`Event` handler]() function. Fires when the browser started loading the resource.
- `onLoadStartCapture`: A version of `onLoadStart` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPause`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause_event): An [`Event` handler]() function. Fires when the media was paused.
- `onPauseCapture`: A version of `onPause` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPlay`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play_event): An [`Event` handler]() function. Fires when the media is no longer paused.
- `onPlayCapture`: A version of `onPlay` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onPlaying`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playing_event): An [`Event` handler]() function. Fires when the media starts or restarts playing.
- `onPlayingCapture`: A version of `onPlaying` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onProgress`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/progress_event): An [`Event` handler]() function. Fires periodically while the resource is loading.
- `onProgressCapture`: A version of `onProgress` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onRateChange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ratechange_event): An [`Event` handler]() function. Fires when playback rate changes.
- `onRateChangeCapture`: A version of `onRateChange` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- `onResize`: An [`Event` handler]() function. Fires when video changes size.
- `onResizeCapture`: A version of `onResize` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onSeeked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeked_event): An [`Event` handler]() function. Fires when a seek operation completes.
- `onSeekedCapture`: A version of `onSeeked` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onSeeking`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeking_event): An [`Event` handler]() function. Fires when a seek operation starts.
- `onSeekingCapture`: A version of `onSeeking` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onStalled`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/stalled_event): An [`Event` handler]() function. Fires when the browser is waiting for data but it keeps not loading.
- `onStalledCapture`: A version of `onStalled` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onSuspend`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/suspend_event): An [`Event` handler]() function. Fires when loading the resource was suspended.
- `onSuspendCapture`: A version of `onSuspend` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onTimeUpdate`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event): An [`Event` handler]() function. Fires when the current playback time updates.
- `onTimeUpdateCapture`: A version of `onTimeUpdate` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onVolumeChange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/volumechange_event): An [`Event` handler]() function. Fires when the volume has changed.
- `onVolumeChangeCapture`: A version of `onVolumeChange` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
- [`onWaiting`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/waiting_event): An [`Event` handler]() function. Fires when the playback stopped due to temporary lack of data.
- `onWaitingCapture`: A version of `onWaiting` that fires in the [capture phase.](https://react.dev/learn/responding-to-events)
#### Caveats[Link for Caveats]()
- You cannot pass both `children` and `dangerouslySetInnerHTML` at the same time.
- Some events (like `onAbort` and `onLoad`) don’t bubble in the browser, but bubble in React.
* * *
### `ref` callback function[Link for this heading]()
Instead of a ref object (like the one returned by [`useRef`](https://react.dev/reference/react/useRef)), you may pass a function to the `ref` attribute.
```
<div ref={(node) => {
console.log('Attached', node);
return () => {
console.log('Clean up', node)
}
}}>
```
[See an example of using the `ref` callback.](https://react.dev/learn/manipulating-the-dom-with-refs)
When the `<div>` DOM node is added to the screen, React will call your `ref` callback with the DOM `node` as the argument. When that `<div>` DOM node is removed, React will call your the cleanup function returned from the callback.
React will also call your `ref` callback whenever you pass a *different* `ref` callback. In the above example, `(node) => { ... }` is a different function on every render. When your component re-renders, the *previous* function will be called with `null` as the argument, and the *next* function will be called with the DOM node.
#### Parameters[Link for Parameters]()
- `node`: A DOM node. React will pass you the DOM node when the ref gets attached. Unless you pass the same function reference for the `ref` callback on every render, the callback will get temporarily cleanup and re-create during every re-render of the component.
### Note
#### React 19 added cleanup functions for `ref` callbacks.[Link for this heading]()
To support backwards compatibility, if a cleanup function is not returned from the `ref` callback, `node` will be called with `null` when the `ref` is detached. This behavior will be removed in a future version.
#### Returns[Link for Returns]()
- **optional** `cleanup function`: When the `ref` is detached, React will call the cleanup function. If a function is not returned by the `ref` callback, React will call the callback again with `null` as the argument when the `ref` gets detached. This behavior will be removed in a future version.
#### Caveats[Link for Caveats]()
- When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic “mirrors” your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, implement the cleanup function.
- When you pass a *different* `ref` callback, React will call the *previous* callback’s cleanup function if provided. If no cleanup function is defined, the `ref` callback will be called with `null` as the argument. The *next* function will be called with the DOM node.
* * *
### React event object[Link for React event object]()
Your event handlers will receive a *React event object.* It is also sometimes known as a “synthetic event”.
```
<button onClick={e => {
console.log(e); // React event object
}} />
```
It conforms to the same standard as the underlying DOM events, but fixes some browser inconsistencies.
Some React events do not map directly to the browser’s native events. For example in `onMouseLeave`, `e.nativeEvent` will point to a `mouseout` event. The specific mapping is not part of the public API and may change in the future. If you need the underlying browser event for some reason, read it from `e.nativeEvent`.
#### Properties[Link for Properties]()
React event objects implement some of the standard [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) properties:
- [`bubbles`](https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles): A boolean. Returns whether the event bubbles through the DOM.
- [`cancelable`](https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable): A boolean. Returns whether the event can be canceled.
- [`currentTarget`](https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget): A DOM node. Returns the node to which the current handler is attached in the React tree.
- [`defaultPrevented`](https://developer.mozilla.org/en-US/docs/Web/API/Event/defaultPrevented): A boolean. Returns whether `preventDefault` was called.
- [`eventPhase`](https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase): A number. Returns which phase the event is currently in.
- [`isTrusted`](https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted): A boolean. Returns whether the event was initiated by user.
- [`target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target): A DOM node. Returns the node on which the event has occurred (which could be a distant child).
- [`timeStamp`](https://developer.mozilla.org/en-US/docs/Web/API/Event/timeStamp): A number. Returns the time when the event occurred.
Additionally, React event objects provide these properties:
- `nativeEvent`: A DOM [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event). The original browser event object.
#### Methods[Link for Methods]()
React event objects implement some of the standard [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) methods:
- [`preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault): Prevents the default browser action for the event.
- [`stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation): Stops the event propagation through the React tree.
Additionally, React event objects provide these methods:
- `isDefaultPrevented()`: Returns a boolean value indicating whether `preventDefault` was called.
- `isPropagationStopped()`: Returns a boolean value indicating whether `stopPropagation` was called.
- `persist()`: Not used with React DOM. With React Native, call this to read event’s properties after the event.
- `isPersistent()`: Not used with React DOM. With React Native, returns whether `persist` has been called.
#### Caveats[Link for Caveats]()
- The values of `currentTarget`, `eventPhase`, `target`, and `type` reflect the values your React code expects. Under the hood, React attaches event handlers at the root, but this is not reflected in React event objects. For example, `e.currentTarget` may not be the same as the underlying `e.nativeEvent.currentTarget`. For polyfilled events, `e.type` (React event type) may differ from `e.nativeEvent.type` (underlying type).
* * *
### `AnimationEvent` handler function[Link for this heading]()
An event handler type for the [CSS animation](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations) events.
```
<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`AnimationEvent`](https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent) properties:
- [`animationName`](https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent/animationName)
- [`elapsedTime`](https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent/elapsedTime)
- [`pseudoElement`](https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent/pseudoElement)
* * *
### `ClipboardEvent` handler function[Link for this heading]()
An event handler type for the [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) events.
```
<input
onCopy={e => console.log('onCopy')}
onCut={e => console.log('onCut')}
onPaste={e => console.log('onPaste')}
/>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`ClipboardEvent`](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent) properties:
- [`clipboardData`](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent/clipboardData)
* * *
### `CompositionEvent` handler function[Link for this heading]()
An event handler type for the [input method editor (IME)](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor) events.
```
<input
onCompositionStart={e => console.log('onCompositionStart')}
onCompositionUpdate={e => console.log('onCompositionUpdate')}
onCompositionEnd={e => console.log('onCompositionEnd')}
/>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`CompositionEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent) properties:
- [`data`](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent/data)
* * *
### `DragEvent` handler function[Link for this heading]()
An event handler type for the [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API) events.
```
<>
<div
draggable={true}
onDragStart={e => console.log('onDragStart')}
onDragEnd={e => console.log('onDragEnd')}
>
Drag source
</div>
<div
onDragEnter={e => console.log('onDragEnter')}
onDragLeave={e => console.log('onDragLeave')}
onDragOver={e => { e.preventDefault(); console.log('onDragOver'); }}
onDrop={e => console.log('onDrop')}
>
Drop target
</div>
</>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`DragEvent`](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent) properties:
- [`dataTransfer`](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/dataTransfer)
It also includes the inherited [`MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) properties:
- [`altKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey)
- [`button`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button)
- [`buttons`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons)
- [`ctrlKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey)
- [`clientX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX)
- [`clientY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)
- [`getModifierState(key)`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/getModifierState)
- [`metaKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/metaKey)
- [`movementX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX)
- [`movementY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementY)
- [`pageX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX)
- [`pageY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageY)
- [`relatedTarget`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget)
- [`screenX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenX)
- [`screenY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenY)
- [`shiftKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/shiftKey)
It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
### `FocusEvent` handler function[Link for this heading]()
An event handler type for the focus events.
```
<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>
```
[See an example.]()
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`FocusEvent`](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent) properties:
- [`relatedTarget`](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/relatedTarget)
It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
### `Event` handler function[Link for this heading]()
An event handler type for generic events.
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with no additional properties.
* * *
### `InputEvent` handler function[Link for this heading]()
An event handler type for the `onBeforeInput` event.
```
<input onBeforeInput={e => console.log('onBeforeInput')} />
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`InputEvent`](https://developer.mozilla.org/en-US/docs/Web/API/InputEvent) properties:
- [`data`](https://developer.mozilla.org/en-US/docs/Web/API/InputEvent/data)
* * *
### `KeyboardEvent` handler function[Link for this heading]()
An event handler type for keyboard events.
```
<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>
```
[See an example.]()
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`KeyboardEvent`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) properties:
- [`altKey`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/altKey)
- [`charCode`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/charCode)
- [`code`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code)
- [`ctrlKey`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/ctrlKey)
- [`getModifierState(key)`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState)
- [`key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
- [`keyCode`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode)
- [`locale`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/locale)
- [`metaKey`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey)
- [`location`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/location)
- [`repeat`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat)
- [`shiftKey`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/shiftKey)
- [`which`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which)
It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
### `MouseEvent` handler function[Link for this heading]()
An event handler type for mouse events.
```
<div
onClick={e => console.log('onClick')}
onMouseEnter={e => console.log('onMouseEnter')}
onMouseOver={e => console.log('onMouseOver')}
onMouseDown={e => console.log('onMouseDown')}
onMouseUp={e => console.log('onMouseUp')}
onMouseLeave={e => console.log('onMouseLeave')}
/>
```
[See an example.]()
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) properties:
- [`altKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey)
- [`button`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button)
- [`buttons`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons)
- [`ctrlKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey)
- [`clientX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX)
- [`clientY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)
- [`getModifierState(key)`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/getModifierState)
- [`metaKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/metaKey)
- [`movementX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX)
- [`movementY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementY)
- [`pageX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX)
- [`pageY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageY)
- [`relatedTarget`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget)
- [`screenX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenX)
- [`screenY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenY)
- [`shiftKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/shiftKey)
It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
### `PointerEvent` handler function[Link for this heading]()
An event handler type for [pointer events.](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events)
```
<div
onPointerEnter={e => console.log('onPointerEnter')}
onPointerMove={e => console.log('onPointerMove')}
onPointerDown={e => console.log('onPointerDown')}
onPointerUp={e => console.log('onPointerUp')}
onPointerLeave={e => console.log('onPointerLeave')}
/>
```
[See an example.]()
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`PointerEvent`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent) properties:
- [`height`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height)
- [`isPrimary`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary)
- [`pointerId`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId)
- [`pointerType`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType)
- [`pressure`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure)
- [`tangentialPressure`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tangentialPressure)
- [`tiltX`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX)
- [`tiltY`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY)
- [`twist`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/twist)
- [`width`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width)
It also includes the inherited [`MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) properties:
- [`altKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey)
- [`button`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button)
- [`buttons`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons)
- [`ctrlKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey)
- [`clientX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX)
- [`clientY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)
- [`getModifierState(key)`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/getModifierState)
- [`metaKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/metaKey)
- [`movementX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX)
- [`movementY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementY)
- [`pageX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX)
- [`pageY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageY)
- [`relatedTarget`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget)
- [`screenX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenX)
- [`screenY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenY)
- [`shiftKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/shiftKey)
It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
### `TouchEvent` handler function[Link for this heading]()
An event handler type for [touch events.](https://developer.mozilla.org/en-US/docs/Web/API/Touch_events)
```
<div
onTouchStart={e => console.log('onTouchStart')}
onTouchMove={e => console.log('onTouchMove')}
onTouchEnd={e => console.log('onTouchEnd')}
onTouchCancel={e => console.log('onTouchCancel')}
/>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`TouchEvent`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent) properties:
- [`altKey`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/altKey)
- [`ctrlKey`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/ctrlKey)
- [`changedTouches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches)
- [`getModifierState(key)`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/getModifierState)
- [`metaKey`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/metaKey)
- [`shiftKey`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/shiftKey)
- [`touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches)
- [`targetTouches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/targetTouches)
It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
### `TransitionEvent` handler function[Link for this heading]()
An event handler type for the CSS transition events.
```
<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`TransitionEvent`](https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent) properties:
- [`elapsedTime`](https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent/elapsedTime)
- [`propertyName`](https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent/propertyName)
- [`pseudoElement`](https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent/pseudoElement)
* * *
### `UIEvent` handler function[Link for this heading]()
An event handler type for generic UI events.
```
<div
onScroll={e => console.log('onScroll')}
/>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
### `WheelEvent` handler function[Link for this heading]()
An event handler type for the `onWheel` event.
```
<div
onWheel={e => console.log('onWheel')}
/>
```
#### Parameters[Link for Parameters]()
- `e`: A [React event object]() with these extra [`WheelEvent`](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent) properties:
- [`deltaMode`](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode)
- [`deltaX`](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaX)
- [`deltaY`](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaY)
- [`deltaZ`](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaZ)
It also includes the inherited [`MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) properties:
- [`altKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey)
- [`button`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button)
- [`buttons`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons)
- [`ctrlKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey)
- [`clientX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX)
- [`clientY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)
- [`getModifierState(key)`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/getModifierState)
- [`metaKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/metaKey)
- [`movementX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX)
- [`movementY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementY)
- [`pageX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX)
- [`pageY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageY)
- [`relatedTarget`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget)
- [`screenX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenX)
- [`screenY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenY)
- [`shiftKey`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/shiftKey)
It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties:
- [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail)
- [`view`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view)
* * *
## Usage[Link for Usage]()
### Applying CSS styles[Link for Applying CSS styles]()
In React, you specify a CSS class with [`className`.](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) It works like the `class` attribute in HTML:
```
<img className="avatar" />
```
Then you write the CSS rules for it in a separate CSS file:
```
/* In your CSS */
.avatar {
border-radius: 50%;
}
```
React does not prescribe how you add CSS files. In the simplest case, you’ll add a [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.
Sometimes, the style values depend on data. Use the `style` attribute to pass some styles dynamically:
```
<img
className="avatar"
style={{
width: user.imageSize,
height: user.imageSize
}}
/>
```
In the above example, `style={{}}` is not a special syntax, but a regular `{}` object inside the `style={ }` [JSX curly braces.](https://react.dev/learn/javascript-in-jsx-with-curly-braces) We recommend only using the `style` attribute when your styles depend on JavaScript variables.
App.jsAvatar.js
Avatar.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function Avatar({ user }) {
return (
<img
src={user.imageUrl}
alt={'Photo of ' + user.name}
className="avatar"
style={{
width: user.imageSize,
height: user.imageSize
}}
/>
);
}
```
##### Deep Dive
#### How to apply multiple CSS classes conditionally?[Link for How to apply multiple CSS classes conditionally?]()
Show Details
To apply CSS classes conditionally, you need to produce the `className` string yourself using JavaScript.
For example, `className={'row ' + (isSelected ? 'selected': '')}` will produce either `className="row"` or `className="row selected"` depending on whether `isSelected` is `true`.
To make this more readable, you can use a tiny helper library like [`classnames`:](https://github.com/JedWatson/classnames)
```
import cn from 'classnames';
function Row({ isSelected }) {
return (
<div className={cn('row', isSelected && 'selected')}>
...
</div>
);
}
```
It is especially convenient if you have multiple conditional classes:
```
import cn from 'classnames';
function Row({ isSelected, size }) {
return (
<div className={cn('row', {
selected: isSelected,
large: size === 'large',
small: size === 'small',
})}>
...
</div>
);
}
```
* * *
### Manipulating a DOM node with a ref[Link for Manipulating a DOM node with a ref]()
Sometimes, you’ll need to get the browser DOM node associated with a tag in JSX. For example, if you want to focus an `<input>` when a button is clicked, you need to call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the browser `<input>` DOM node.
To obtain the browser DOM node for a tag, [declare a ref](https://react.dev/reference/react/useRef) and pass it as the `ref` attribute to that tag:
```
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
// ...
return (
<input ref={inputRef} />
// ...
```
React will put the DOM node into `inputRef.current` after it’s been rendered to the screen.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>
Focus the input
</button>
</>
);
}
```
Show more
Read more about [manipulating DOM with refs](https://react.dev/learn/manipulating-the-dom-with-refs) and [check out more examples.](https://react.dev/reference/react/useRef)
For more advanced use cases, the `ref` attribute also accepts a [callback function.]()
* * *
### Dangerously setting the inner HTML[Link for Dangerously setting the inner HTML]()
You can pass a raw HTML string to an element like so:
```
const markup = { __html: '<p>some raw html</p>' };
return <div dangerouslySetInnerHTML={markup} />;
```
**This is dangerous. As with the underlying DOM [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) property, you must exercise extreme caution! Unless the markup is coming from a completely trusted source, it is trivial to introduce an [XSS](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerability this way.**
For example, if you use a Markdown library that converts Markdown to HTML, you trust that its parser doesn’t contain bugs, and the user only sees their own input, you can display the resulting HTML like this:
package.jsonApp.jsMarkdownPreview.js
MarkdownPreview.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { Remarkable } from 'remarkable';
const md = new Remarkable();
function renderMarkdownToHTML(markdown) {
// This is ONLY safe because the output HTML
// is shown to the same user, and because you
// trust this Markdown parser to not have bugs.
const renderedHTML = md.render(markdown);
return {__html: renderedHTML};
}
export default function MarkdownPreview({ markdown }) {
const markup = renderMarkdownToHTML(markdown);
return <div dangerouslySetInnerHTML={markup} />;
}
```
Show more
The `{__html}` object should be created as close to where the HTML is generated as possible, like the above example does in the `renderMarkdownToHTML` function. This ensures that all raw HTML being used in your code is explicitly marked as such, and that only variables that you expect to contain HTML are passed to `dangerouslySetInnerHTML`. It is not recommended to create the object inline like `<div dangerouslySetInnerHTML={{__html: markup}} />`.
To see why rendering arbitrary HTML is dangerous, replace the code above with this:
```
const post = {
// Imagine this content is stored in the database.
content: `<img src="" onerror='alert("you were hacked")'>`
};
export default function MarkdownPreview() {
// 🔴 SECURITY HOLE: passing untrusted input to dangerouslySetInnerHTML
const markup = { __html: post.content };
return <div dangerouslySetInnerHTML={markup} />;
}
```
The code embedded in the HTML will run. A hacker could use this security hole to steal user information or to perform actions on their behalf. **Only use `dangerouslySetInnerHTML` with trusted and sanitized data.**
* * *
### Handling mouse events[Link for Handling mouse events]()
This example shows some common [mouse events]() and when they fire.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function MouseExample() {
return (
<div
onMouseEnter={e => console.log('onMouseEnter (parent)')}
onMouseLeave={e => console.log('onMouseLeave (parent)')}
>
<button
onClick={e => console.log('onClick (first button)')}
onMouseDown={e => console.log('onMouseDown (first button)')}
onMouseEnter={e => console.log('onMouseEnter (first button)')}
onMouseLeave={e => console.log('onMouseLeave (first button)')}
onMouseOver={e => console.log('onMouseOver (first button)')}
onMouseUp={e => console.log('onMouseUp (first button)')}
>
First button
</button>
<button
onClick={e => console.log('onClick (second button)')}
onMouseDown={e => console.log('onMouseDown (second button)')}
onMouseEnter={e => console.log('onMouseEnter (second button)')}
onMouseLeave={e => console.log('onMouseLeave (second button)')}
onMouseOver={e => console.log('onMouseOver (second button)')}
onMouseUp={e => console.log('onMouseUp (second button)')}
>
Second button
</button>
</div>
);
}
```
Show more
* * *
### Handling pointer events[Link for Handling pointer events]()
This example shows some common [pointer events]() and when they fire.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function PointerExample() {
return (
<div
onPointerEnter={e => console.log('onPointerEnter (parent)')}
onPointerLeave={e => console.log('onPointerLeave (parent)')}
style={{ padding: 20, backgroundColor: '#ddd' }}
>
<div
onPointerDown={e => console.log('onPointerDown (first child)')}
onPointerEnter={e => console.log('onPointerEnter (first child)')}
onPointerLeave={e => console.log('onPointerLeave (first child)')}
onPointerMove={e => console.log('onPointerMove (first child)')}
onPointerUp={e => console.log('onPointerUp (first child)')}
style={{ padding: 20, backgroundColor: 'lightyellow' }}
>
First child
</div>
<div
onPointerDown={e => console.log('onPointerDown (second child)')}
onPointerEnter={e => console.log('onPointerEnter (second child)')}
onPointerLeave={e => console.log('onPointerLeave (second child)')}
onPointerMove={e => console.log('onPointerMove (second child)')}
onPointerUp={e => console.log('onPointerUp (second child)')}
style={{ padding: 20, backgroundColor: 'lightblue' }}
>
Second child
</div>
</div>
);
}
```
Show more
* * *
### Handling focus events[Link for Handling focus events]()
In React, [focus events]() bubble. You can use the `currentTarget` and `relatedTarget` to differentiate if the focusing or blurring events originated from outside of the parent element. The example shows how to detect focusing a child, focusing the parent element, and how to detect focus entering or leaving the whole subtree.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function FocusExample() {
return (
<div
tabIndex={1}
onFocus={(e) => {
if (e.currentTarget === e.target) {
console.log('focused parent');
} else {
console.log('focused child', e.target.name);
}
if (!e.currentTarget.contains(e.relatedTarget)) {
// Not triggered when swapping focus between children
console.log('focus entered parent');
}
}}
onBlur={(e) => {
if (e.currentTarget === e.target) {
console.log('unfocused parent');
} else {
console.log('unfocused child', e.target.name);
}
if (!e.currentTarget.contains(e.relatedTarget)) {
// Not triggered when swapping focus between children
console.log('focus left parent');
}
}}
>
<label>
First name:
<input name="firstName" />
</label>
<label>
Last name:
<input name="lastName" />
</label>
</div>
);
}
```
Show more
* * *
### Handling keyboard events[Link for Handling keyboard events]()
This example shows some common [keyboard events]() and when they fire.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function KeyboardExample() {
return (
<label>
First name:
<input
name="firstName"
onKeyDown={e => console.log('onKeyDown:', e.key, e.code)}
onKeyUp={e => console.log('onKeyUp:', e.key, e.code)}
/>
</label>
);
}
```
[PreviousComponents](https://react.dev/reference/react-dom/components)
[Next<form>](https://react.dev/reference/react-dom/components/form) |
https://react.dev/reference/react-dom/components/link | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <link>[Link for this heading]()
The [built-in browser `<link>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) lets you use external resources such as stylesheets or annotate the document with link metadata.
```
<link rel="icon" href="favicon.ico" />
```
- [Reference]()
- [`<link>`]()
- [Usage]()
- [Linking to related resources]()
- [Linking to a stylesheet]()
- [Controlling stylesheet precedence]()
- [Deduplicated stylesheet rendering]()
- [Annotating specific items within the document with links]()
* * *
## Reference[Link for Reference]()
### `<link>`[Link for this heading]()
To link to external resources such as stylesheets, fonts, and icons, or to annotate the document with link metadata, render the [built-in browser `<link>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link). You can render `<link>` from any component and React will [in most cases]() place the corresponding DOM element in the document head.
```
<link rel="icon" href="favicon.ico" />
```
[See more examples below.]()
#### Props[Link for Props]()
`<link>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
- `rel`: a string, required. Specifies the [relationship to the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel). React [treats links with `rel="stylesheet"` differently]() from other links.
These props apply when `rel="stylesheet"`:
- `precedence`: a string. Tells React where to rank the `<link>` DOM node relative to others in the document `<head>`, which determines which stylesheet can override the other. React will infer that precedence values it discovers first are “lower” and precedence values it discovers later are “higher”. Many style systems can work fine using a single precedence value because style rules are atomic. Stylesheets with the same precedence go together whether they are `<link>` or inline `<style>` tags or loaded using [`preinit`](https://react.dev/reference/react-dom/preinit) functions.
- `media`: a string. Restricts the stylesheet to a certain [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries).
- `title`: a string. Specifies the name of an [alternative stylesheet](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets).
These props apply when `rel="stylesheet"` but disable React’s [special treatment of stylesheets]():
- `disabled`: a boolean. Disables the stylesheet.
- `onError`: a function. Called when the stylesheet fails to load.
- `onLoad`: a function. Called when the stylesheet finishes being loaded.
These props apply when `rel="preload"` or `rel="modulepreload"`:
- `as`: a string. The type of resource. Its possible values are `audio`, `document`, `embed`, `fetch`, `font`, `image`, `object`, `script`, `style`, `track`, `video`, `worker`.
- `imageSrcSet`: a string. Applicable only when `as="image"`. Specifies the [source set of the image](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).
- `imageSizes`: a string. Applicable only when `as="image"`. Specifies the [sizes of the image](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).
These props apply when `rel="icon"` or `rel="apple-touch-icon"`:
- `sizes`: a string. The [sizes of the icon](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).
These props apply in all cases:
- `href`: a string. The URL of the linked resource.
- `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`. It is required when `as` is set to `"fetch"`.
- `referrerPolicy`: a string. The [Referrer header](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) to send when fetching. Its possible values are `no-referrer-when-downgrade` (the default), `no-referrer`, `origin`, `origin-when-cross-origin`, and `unsafe-url`.
- `fetchPriority`: a string. Suggests a relative priority for fetching the resource. The possible values are `auto` (the default), `high`, and `low`.
- `hrefLang`: a string. The language of the linked resource.
- `integrity`: a string. A cryptographic hash of the resource, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
- `type`: a string. The MIME type of the linked resource.
Props that are **not recommended** for use with React:
- `blocking`: a string. If set to `"render"`, instructs the browser not to render the page until the stylesheet is loaded. React provides more fine-grained control using Suspense.
#### Special rendering behavior[Link for Special rendering behavior]()
React will always place the DOM element corresponding to the `<link>` component within the document’s `<head>`, regardless of where in the React tree it is rendered. The `<head>` is the only valid place for `<link>` to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render `<link>` components itself.
There are a few exceptions to this:
- If the `<link>` has a `rel="stylesheet"` prop, then it has to also have a `precedence` prop to get this special behavior. This is because the order of stylesheets within the document is significant, so React needs to know how to order this stylesheet relative to others, which you specify using the `precedence` prop. If the `precedence` prop is omitted, there is no special behavior.
- If the `<link>` has an [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop) prop, there is no special behavior, because in this case it doesn’t apply to the document but instead represents metadata about a specific part of the page.
- If the `<link>` has an `onLoad` or `onError` prop, because in that case you are managing the loading of the linked resource manually within your React component.
#### Special behavior for stylesheets[Link for Special behavior for stylesheets]()
In addition, if the `<link>` is to a stylesheet (namely, it has `rel="stylesheet"` in its props), React treats it specially in the following ways:
- The component that renders `<link>` will [suspend](https://react.dev/reference/react/Suspense) while the stylesheet is loading.
- If multiple components render links to the same stylesheet, React will de-duplicate them and only put a single link into the DOM. Two links are considered the same if they have the same `href` prop.
There are two exception to this special behavior:
- If the link doesn’t have a `precedence` prop, there is no special behavior, because the order of stylesheets within the document is significant, so React needs to know how to order this stylesheet relative to others, which you specify using the `precedence` prop.
- If you supply any of the `onLoad`, `onError`, or `disabled` props, there is no special behavior, because these props indicate that you are managing the loading of the stylesheet manually within your component.
This special treatment comes with two caveats:
- React will ignore changes to props after the link has been rendered. (React will issue a warning in development if this happens.)
- React may leave the link in the DOM even after the component that rendered it has been unmounted.
* * *
## Usage[Link for Usage]()
### Linking to related resources[Link for Linking to related resources]()
You can annotate the document with links to related resources such as an icon, canonical URL, or pingback. React will place this metadata within the document `<head>` regardless of where in the React tree it is rendered.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
export default function BlogPage() {
return (
<ShowRenderedHTML>
<link rel="icon" href="favicon.ico" />
<link rel="pingback" href="http://www.example.com/xmlrpc.php" />
<h1>My Blog</h1>
<p>...</p>
</ShowRenderedHTML>
);
}
```
### Linking to a stylesheet[Link for Linking to a stylesheet]()
If a component depends on a certain stylesheet in order to be displayed correctly, you can render a link to that stylesheet within the component. Your component will [suspend](https://react.dev/reference/react/Suspense) while the stylesheet is loading. You must supply the `precedence` prop, which tells React where to place this stylesheet relative to others — stylesheets with higher precedence can override those with lower precedence.
### Note
When you want to use a stylesheet, it can be beneficial to call the [preinit](https://react.dev/reference/react-dom/preinit) function. Calling this function may allow the browser to start fetching the stylesheet earlier than if you just render a `<link>` component, for example by sending an [HTTP Early Hints response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103).
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
export default function SiteMapPage() {
return (
<ShowRenderedHTML>
<link rel="stylesheet" href="sitemap.css" precedence="medium" />
<p>...</p>
</ShowRenderedHTML>
);
}
```
### Controlling stylesheet precedence[Link for Controlling stylesheet precedence]()
Stylesheets can conflict with each other, and when they do, the browser goes with the one that comes later in the document. React lets you control the order of stylesheets with the `precedence` prop. In this example, three components render stylesheets, and the ones with the same precedence are grouped together in the `<head>`.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
export default function HomePage() {
return (
<ShowRenderedHTML>
<FirstComponent />
<SecondComponent />
<ThirdComponent/>
...
</ShowRenderedHTML>
);
}
function FirstComponent() {
return <link rel="stylesheet" href="first.css" precedence="first" />;
}
function SecondComponent() {
return <link rel="stylesheet" href="second.css" precedence="second" />;
}
function ThirdComponent() {
return <link rel="stylesheet" href="third.css" precedence="first" />;
}
```
Show more
Note the `precedence` values themselves are arbitrary and their naming is up to you. React will infer that precedence values it discovers first are “lower” and precedence values it discovers later are “higher”.
### Deduplicated stylesheet rendering[Link for Deduplicated stylesheet rendering]()
If you render the same stylesheet from multiple components, React will place only a single `<link>` in the document head.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
export default function HomePage() {
return (
<ShowRenderedHTML>
<Component />
<Component />
...
</ShowRenderedHTML>
);
}
function Component() {
return <link rel="stylesheet" href="styles.css" precedence="medium" />;
}
```
### Annotating specific items within the document with links[Link for Annotating specific items within the document with links]()
You can use the `<link>` component with the `itemProp` prop to annotate specific items within the document with links to related resources. In this case, React will *not* place these annotations within the document `<head>` but will place them like any other React component.
```
<section itemScope>
<h3>Annotating specific items</h3>
<link itemProp="author" href="http://example.com/" />
<p>...</p>
</section>
```
[Previous<textarea>](https://react.dev/reference/react-dom/components/textarea)
[Next<meta>](https://react.dev/reference/react-dom/components/meta) |
https://react.dev/reference/react-dom/components/progress | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <progress>[Link for this heading]()
The [built-in browser `<progress>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) lets you render a progress indicator.
```
<progress value={0.5} />
```
- [Reference]()
- [`<progress>`]()
- [Usage]()
- [Controlling a progress indicator]()
* * *
## Reference[Link for Reference]()
### `<progress>`[Link for this heading]()
To display a progress indicator, render the [built-in browser `<progress>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) component.
```
<progress value={0.5} />
```
[See more examples below.]()
#### Props[Link for Props]()
`<progress>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
Additionally, `<progress>` supports these props:
- [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress): A number. Specifies the maximum `value`. Defaults to `1`.
- [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress): A number between `0` and `max`, or `null` for indeterminate progress. Specifies how much was done.
* * *
## Usage[Link for Usage]()
### Controlling a progress indicator[Link for Controlling a progress indicator]()
To display a progress indicator, render a `<progress>` component. You can pass a number `value` between `0` and the `max` value you specify. If you don’t pass a `max` value, it will assumed to be `1` by default.
If the operation is not ongoing, pass `value={null}` to put the progress indicator into an indeterminate state.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function App() {
return (
<>
<progress value={0} />
<progress value={0.5} />
<progress value={0.7} />
<progress value={75} max={100} />
<progress value={1} />
<progress value={null} />
</>
);
}
```
[Previous<option>](https://react.dev/reference/react-dom/components/option)
[Next<select>](https://react.dev/reference/react-dom/components/select) |
https://react.dev/reference/react-dom/components/style | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <style>[Link for this heading]()
The [built-in browser `<style>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) lets you add inline CSS stylesheets to your document.
```
<style>{` p { color: red; } `}</style>
```
- [Reference]()
- [`<style>`]()
- [Usage]()
- [Rendering an inline CSS stylesheet]()
* * *
## Reference[Link for Reference]()
### `<style>`[Link for this heading]()
To add inline styles to your document, render the [built-in browser `<style>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style). You can render `<style>` from any component and React will [in certain cases]() place the corresponding DOM element in the document head and de-duplicate identical styles.
```
<style>{` p { color: red; } `}</style>
```
[See more examples below.]()
#### Props[Link for Props]()
`<style>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
- `children`: a string, required. The contents of the stylesheet.
- `precedence`: a string. Tells React where to rank the `<style>` DOM node relative to others in the document `<head>`, which determines which stylesheet can override the other. React will infer that precedence values it discovers first are “lower” and precedence values it discovers later are “higher”. Many style systems can work fine using a single precedence value because style rules are atomic. Stylesheets with the same precedence go together whether they are `<link>` or inline `<style>` tags or loaded using [`preinit`](https://react.dev/reference/react-dom/preinit) functions.
- `href`: a string. Allows React to [de-duplicate styles]() that have the same `href`.
- `media`: a string. Restricts the stylesheet to a certain [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries).
- `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
- `title`: a string. Specifies the name of an [alternative stylesheet](https://developer.mozilla.org/en-US/docs/Web/CSS/Alternative_style_sheets).
Props that are **not recommended** for use with React:
- `blocking`: a string. If set to `"render"`, instructs the browser not to render the page until the stylesheet is loaded. React provides more fine-grained control using Suspense.
#### Special rendering behavior[Link for Special rendering behavior]()
React can move `<style>` components to the document’s `<head>`, de-duplicate identical stylesheets, and [suspend](https://react.dev/reference/react/Suspense) while the stylesheet is loading.
To opt into this behavior, provide the `href` and `precedence` props. React will de-duplicate styles if they have the same `href`. The precedence prop tells React where to rank the `<style>` DOM node relative to others in the document `<head>`, which determines which stylesheet can override the other.
This special treatment comes with two caveats:
- React will ignore changes to props after the style has been rendered. (React will issue a warning in development if this happens.)
- React may leave the style in the DOM even after the component that rendered it has been unmounted.
* * *
## Usage[Link for Usage]()
### Rendering an inline CSS stylesheet[Link for Rendering an inline CSS stylesheet]()
If a component depends on certain CSS styles in order to be displayed correctly, you can render an inline stylesheet within the component.
The `href` prop should uniquely identify the stylesheet, because React will de-duplicate stylesheets that have the same `href`. If you supply a `precedence` prop, React will reorder inline stylesheets based on the order these values appear in the component tree.
Inline stylesheets will not trigger Suspense boundaries while they’re loading. Even if they load async resources like fonts or images.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
import { useId } from 'react';
function PieChart({data, colors}) {
const id = useId();
const stylesheet = colors.map((color, index) =>
`#${id} .color-${index}: \{ color: "${color}"; \}`
).join();
return (
<>
<style href={"PieChart-" + JSON.stringify(colors)} precedence="medium">
{stylesheet}
</style>
<svg id={id}>
…
</svg>
</>
);
}
export default function App() {
return (
<ShowRenderedHTML>
<PieChart data="..." colors={['red', 'green', 'blue']} />
</ShowRenderedHTML>
);
}
```
Show more
[Previous<script>](https://react.dev/reference/react-dom/components/script)
[Next<title>](https://react.dev/reference/react-dom/components/title) |
https://react.dev/reference/react-dom/components/meta | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <meta>[Link for this heading]()
The [built-in browser `<meta>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) lets you add metadata to the document.
```
<meta name="keywords" content="React, JavaScript, semantic markup, html" />
```
- [Reference]()
- [`<meta>`]()
- [Usage]()
- [Annotating the document with metadata]()
- [Annotating specific items within the document with metadata]()
* * *
## Reference[Link for Reference]()
### `<meta>`[Link for this heading]()
To add document metadata, render the [built-in browser `<meta>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). You can render `<meta>` from any component and React will always place the corresponding DOM element in the document head.
```
<meta name="keywords" content="React, JavaScript, semantic markup, html" />
```
[See more examples below.]()
#### Props[Link for Props]()
`<meta>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
It should have *exactly one* of the following props: `name`, `httpEquiv`, `charset`, `itemProp`. The `<meta>` component does something different depending on which of these props is specified.
- `name`: a string. Specifies the [kind of metadata](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name) to be attached to the document.
- `charset`: a string. Specifies the character set used by the document. The only valid value is `"utf-8"`.
- `httpEquiv`: a string. Specifies a directive for processing the document.
- `itemProp`: a string. Specifies metadata about a particular item within the document rather than the document as a whole.
- `content`: a string. Specifies the metadata to be attached when used with the `name` or `itemProp` props or the behavior of the directive when used with the `httpEquiv` prop.
#### Special rendering behavior[Link for Special rendering behavior]()
React will always place the DOM element corresponding to the `<meta>` component within the document’s `<head>`, regardless of where in the React tree it is rendered. The `<head>` is the only valid place for `<meta>` to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render `<meta>` components itself.
There is one exception to this: if `<meta>` has an [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop) prop, there is no special behavior, because in this case it doesn’t represent metadata about the document but rather metadata about a specific part of the page.
* * *
## Usage[Link for Usage]()
### Annotating the document with metadata[Link for Annotating the document with metadata]()
You can annotate the document with metadata such as keywords, a summary, or the author’s name. React will place this metadata within the document `<head>` regardless of where in the React tree it is rendered.
```
<meta name="author" content="John Smith" />
<meta name="keywords" content="React, JavaScript, semantic markup, html" />
<meta name="description" content="API reference for the <meta> component in React DOM" />
```
You can render the `<meta>` component from any component. React will put a `<meta>` DOM node in the document `<head>`.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
export default function SiteMapPage() {
return (
<ShowRenderedHTML>
<meta name="keywords" content="React" />
<meta name="description" content="A site map for the React website" />
<h1>Site Map</h1>
<p>...</p>
</ShowRenderedHTML>
);
}
```
### Annotating specific items within the document with metadata[Link for Annotating specific items within the document with metadata]()
You can use the `<meta>` component with the `itemProp` prop to annotate specific items within the document with metadata. In this case, React will *not* place these annotations within the document `<head>` but will place them like any other React component.
```
<section itemScope>
<h3>Annotating specific items</h3>
<meta itemProp="description" content="API reference for using <meta> with itemProp" />
<p>...</p>
</section>
```
[Previous<link>](https://react.dev/reference/react-dom/components/link)
[Next<script>](https://react.dev/reference/react-dom/components/script) |
https://react.dev/reference/react-dom/components/script | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <script>[Link for this heading]()
The [built-in browser `<script>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) lets you add a script to your document.
```
<script> alert("hi!") </script>
```
- [Reference]()
- [`<script>`]()
- [Usage]()
- [Rendering an external script]()
- [Rendering an inline script]()
* * *
## Reference[Link for Reference]()
### `<script>`[Link for this heading]()
To add inline or external scripts to your document, render the [built-in browser `<script>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script). You can render `<script>` from any component and React will [in certain cases]() place the corresponding DOM element in the document head and de-duplicate identical scripts.
```
<script> alert("hi!") </script>
<script src="script.js" />
```
[See more examples below.]()
#### Props[Link for Props]()
`<script>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
It should have *either* `children` or a `src` prop.
- `children`: a string. The source code of an inline script.
- `src`: a string. The URL of an external script.
Other supported props:
- `async`: a boolean. Allows the browser to defer execution of the script until the rest of the document has been processed — the preferred behavior for performance.
- `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`.
- `fetchPriority`: a string. Lets the browser rank scripts in priority when fetching multiple scripts at the same time. Can be `"high"`, `"low"`, or `"auto"` (the default).
- `integrity`: a string. A cryptographic hash of the script, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
- `noModule`: a boolean. Disables the script in browsers that support ES modules — allowing for a fallback script for browsers that do not.
- `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
- `referrer`: a string. Says [what Referer header to send](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) when fetching the script and any resources that the script fetches in turn.
- `type`: a string. Says whether the script is a [classic script, ES module, or import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type).
Props that disable React’s [special treatment of scripts]():
- `onError`: a function. Called when the script fails to load.
- `onLoad`: a function. Called when the script finishes being loaded.
Props that are **not recommended** for use with React:
- `blocking`: a string. If set to `"render"`, instructs the browser not to render the page until the scriptsheet is loaded. React provides more fine-grained control using Suspense.
- `defer`: a string. Prevents the browser from executing the script until the document is done loading. Not compatible with streaming server-rendered components. Use the `async` prop instead.
#### Special rendering behavior[Link for Special rendering behavior]()
React can move `<script>` components to the document’s `<head>` and de-duplicate identical scripts.
To opt into this behavior, provide the `src` and `async={true}` props. React will de-duplicate scripts if they have the same `src`. The `async` prop must be true to allow scripts to be safely moved.
This special treatment comes with two caveats:
- React will ignore changes to props after the script has been rendered. (React will issue a warning in development if this happens.)
- React may leave the script in the DOM even after the component that rendered it has been unmounted. (This has no effect as scripts just execute once when they are inserted into the DOM.)
* * *
## Usage[Link for Usage]()
### Rendering an external script[Link for Rendering an external script]()
If a component depends on certain scripts in order to be displayed correctly, you can render a `<script>` within the component. However, the component might be committed before the script has finished loading. You can start depending on the script content once the `load` event is fired e.g. by using the `onLoad` prop.
React will de-duplicate scripts that have the same `src`, inserting only one of them into the DOM even if multiple components render it.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
function Map({lat, long}) {
return (
<>
<script async src="map-api.js" onLoad={() => console.log('script loaded')} />
<div id="map" data-lat={lat} data-long={long} />
</>
);
}
export default function Page() {
return (
<ShowRenderedHTML>
<Map />
</ShowRenderedHTML>
);
}
```
Show more
### Note
When you want to use a script, it can be beneficial to call the [preinit](https://react.dev/reference/react-dom/preinit) function. Calling this function may allow the browser to start fetching the script earlier than if you just render a `<script>` component, for example by sending an [HTTP Early Hints response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103).
### Rendering an inline script[Link for Rendering an inline script]()
To include an inline script, render the `<script>` component with the script source code as its children. Inline scripts are not de-duplicated or moved to the document `<head>`.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
function Tracking() {
return (
<script>
ga('send', 'pageview');
</script>
);
}
export default function Page() {
return (
<ShowRenderedHTML>
<h1>My Website</h1>
<Tracking />
<p>Welcome</p>
</ShowRenderedHTML>
);
}
```
Show more
[Previous<meta>](https://react.dev/reference/react-dom/components/meta)
[Next<style>](https://react.dev/reference/react-dom/components/style) |
https://react.dev/reference/react-dom/components/title | [API Reference](https://react.dev/reference/react)
[Components](https://react.dev/reference/react-dom/components)
# <title>[Link for this heading]()
The [built-in browser `<title>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title) lets you specify the title of the document.
```
<title>My Blog</title>
```
- [Reference]()
- [`<title>`]()
- [Usage]()
- [Set the document title]()
- [Use variables in the title]()
* * *
## Reference[Link for Reference]()
### `<title>`[Link for this heading]()
To specify the title of the document, render the [built-in browser `<title>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title). You can render `<title>` from any component and React will always place the corresponding DOM element in the document head.
```
<title>My Blog</title>
```
[See more examples below.]()
#### Props[Link for Props]()
`<title>` supports all [common element props.](https://react.dev/reference/react-dom/components/common)
- `children`: `<title>` accepts only text as a child. This text will become the title of the document. You can also pass your own components as long as they only render text.
#### Special rendering behavior[Link for Special rendering behavior]()
React will always place the DOM element corresponding to the `<title>` component within the document’s `<head>`, regardless of where in the React tree it is rendered. The `<head>` is the only valid place for `<title>` to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render its `<title>` itself.
There are two exception to this:
- If `<title>` is within an `<svg>` component, then there is no special behavior, because in this context it doesn’t represent the document’s title but rather is an [accessibility annotation for that SVG graphic](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/title).
- If the `<title>` has an [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop) prop, there is no special behavior, because in this case it doesn’t represent the document’s title but rather metadata about a specific part of the page.
### Pitfall
Only render a single `<title>` at a time. If more than one component renders a `<title>` tag at the same time, React will place all of those titles in the document head. When this happens, the behavior of browsers and search engines is undefined.
* * *
## Usage[Link for Usage]()
### Set the document title[Link for Set the document title]()
Render the `<title>` component from any component with text as its children. React will put a `<title>` DOM node in the document `<head>`.
App.jsShowRenderedHTML.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import ShowRenderedHTML from './ShowRenderedHTML.js';
export default function ContactUsPage() {
return (
<ShowRenderedHTML>
<title>My Site: Contact Us</title>
<h1>Contact Us</h1>
<p>Email us at [email protected]</p>
</ShowRenderedHTML>
);
}
```
### Use variables in the title[Link for Use variables in the title]()
The children of the `<title>` component must be a single string of text. (Or a single number or a single object with a `toString` method.) It might not be obvious, but using JSX curly braces like this:
```
<title>Results page {pageNumber}</title> // 🔴 Problem: This is not a single string
```
… actually causes the `<title>` component to get a two-element array as its children (the string `"Results page"` and the value of `pageNumber`). This will cause an error. Instead, use string interpolation to pass `<title>` a single string:
```
<title>{`Results page ${pageNumber}`}</title>
```
[Previous<style>](https://react.dev/reference/react-dom/components/style)
[NextAPIs](https://react.dev/reference/react-dom) |
https://react.dev/reference/react-dom/flushSync | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# flushSync[Link for this heading]()
### Pitfall
Using `flushSync` is uncommon and can hurt the performance of your app.
`flushSync` lets you force React to flush any updates inside the provided callback synchronously. This ensures that the DOM is updated immediately.
```
flushSync(callback)
```
- [Reference]()
- [`flushSync(callback)`]()
- [Usage]()
- [Flushing updates for third-party integrations]()
* * *
## Reference[Link for Reference]()
### `flushSync(callback)`[Link for this heading]()
Call `flushSync` to force React to flush any pending work and update the DOM synchronously.
```
import { flushSync } from 'react-dom';
flushSync(() => {
setSomething(123);
});
```
Most of the time, `flushSync` can be avoided. Use `flushSync` as last resort.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `callback`: A function. React will immediately call this callback and flush any updates it contains synchronously. It may also flush any pending updates, or Effects, or updates inside of Effects. If an update suspends as a result of this `flushSync` call, the fallbacks may be re-shown.
#### Returns[Link for Returns]()
`flushSync` returns `undefined`.
#### Caveats[Link for Caveats]()
- `flushSync` can significantly hurt performance. Use sparingly.
- `flushSync` may force pending Suspense boundaries to show their `fallback` state.
- `flushSync` may run pending Effects and synchronously apply any updates they contain before returning.
- `flushSync` may flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback.
* * *
## Usage[Link for Usage]()
### Flushing updates for third-party integrations[Link for Flushing updates for third-party integrations]()
When integrating with third-party code such as browser APIs or UI libraries, it may be necessary to force React to flush updates. Use `flushSync` to force React to flush any state updates inside the callback synchronously:
```
flushSync(() => {
setSomething(123);
});
// By this line, the DOM is updated.
```
This ensures that, by the time the next line of code runs, React has already updated the DOM.
**Using `flushSync` is uncommon, and using it often can significantly hurt the performance of your app.** If your app only uses React APIs, and does not integrate with third-party libraries, `flushSync` should be unnecessary.
However, it can be helpful for integrating with third-party code like browser APIs.
Some browser APIs expect results inside of callbacks to be written to the DOM synchronously, by the end of the callback, so the browser can do something with the rendered DOM. In most cases, React handles this for you automatically. But in some cases it may be necessary to force a synchronous update.
For example, the browser `onbeforeprint` API allows you to change the page immediately before the print dialog opens. This is useful for applying custom print styles that allow the document to display better for printing. In the example below, you use `flushSync` inside of the `onbeforeprint` callback to immediately “flush” the React state to the DOM. Then, by the time the print dialog opens, `isPrinting` displays “yes”:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
export default function PrintApp() {
const [isPrinting, setIsPrinting] = useState(false);
useEffect(() => {
function handleBeforePrint() {
flushSync(() => {
setIsPrinting(true);
})
}
function handleAfterPrint() {
setIsPrinting(false);
}
window.addEventListener('beforeprint', handleBeforePrint);
window.addEventListener('afterprint', handleAfterPrint);
return () => {
window.removeEventListener('beforeprint', handleBeforePrint);
window.removeEventListener('afterprint', handleAfterPrint);
}
}, []);
return (
<>
<h1>isPrinting: {isPrinting ? 'yes' : 'no'}</h1>
<button onClick={() => window.print()}>
Print
</button>
</>
);
}
```
Show more
Without `flushSync`, the print dialog will display `isPrinting` as “no”. This is because React batches the updates asynchronously and the print dialog is displayed before the state is updated.
### Pitfall
`flushSync` can significantly hurt performance, and may unexpectedly force pending Suspense boundaries to show their fallback state.
Most of the time, `flushSync` can be avoided, so use `flushSync` as a last resort.
[PreviouscreatePortal](https://react.dev/reference/react-dom/createPortal)
[Nextpreconnect](https://react.dev/reference/react-dom/preconnect) |
https://react.dev/reference/react-dom/preconnect | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# preconnect[Link for this heading]()
`preconnect` lets you eagerly connect to a server that you expect to load resources from.
```
preconnect("https://example.com");
```
- [Reference]()
- [`preconnect(href)`]()
- [Usage]()
- [Preconnecting when rendering]()
- [Preconnecting in an event handler]()
* * *
## Reference[Link for Reference]()
### `preconnect(href)`[Link for this heading]()
To preconnect to a host, call the `preconnect` function from `react-dom`.
```
import { preconnect } from 'react-dom';
function AppRoot() {
preconnect("https://example.com");
// ...
}
```
[See more examples below.]()
The `preconnect` function provides the browser with a hint that it should open a connection to the given server. If the browser chooses to do so, this can speed up the loading of resources from that server.
#### Parameters[Link for Parameters]()
- `href`: a string. The URL of the server you want to connect to.
#### Returns[Link for Returns]()
`preconnect` returns nothing.
#### Caveats[Link for Caveats]()
- Multiple calls to `preconnect` with the same server have the same effect as a single call.
- In the browser, you can call `preconnect` in any situation: while rendering a component, in an Effect, in an event handler, and so on.
- In server-side rendering or when rendering Server Components, `preconnect` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored.
- If you know the specific resources you’ll need, you can call [other functions](https://react.dev/reference/react-dom) instead that will start loading the resources right away.
- There is no benefit to preconnecting to the same server the webpage itself is hosted from because it’s already been connected to by the time the hint would be given.
* * *
## Usage[Link for Usage]()
### Preconnecting when rendering[Link for Preconnecting when rendering]()
Call `preconnect` when rendering a component if you know that its children will load external resources from that host.
```
import { preconnect } from 'react-dom';
function AppRoot() {
preconnect("https://example.com");
return ...;
}
```
### Preconnecting in an event handler[Link for Preconnecting in an event handler]()
Call `preconnect` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state.
```
import { preconnect } from 'react-dom';
function CallToAction() {
const onClick = () => {
preconnect('http://example.com');
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}
```
[PreviousflushSync](https://react.dev/reference/react-dom/flushSync)
[NextprefetchDNS](https://react.dev/reference/react-dom/prefetchDNS) |
https://react.dev/reference/react-dom/prefetchDNS | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# prefetchDNS[Link for this heading]()
`prefetchDNS` lets you eagerly look up the IP of a server that you expect to load resources from.
```
prefetchDNS("https://example.com");
```
- [Reference]()
- [`prefetchDNS(href)`]()
- [Usage]()
- [Prefetching DNS when rendering]()
- [Prefetching DNS in an event handler]()
* * *
## Reference[Link for Reference]()
### `prefetchDNS(href)`[Link for this heading]()
To look up a host, call the `prefetchDNS` function from `react-dom`.
```
import { prefetchDNS } from 'react-dom';
function AppRoot() {
prefetchDNS("https://example.com");
// ...
}
```
[See more examples below.]()
The prefetchDNS function provides the browser with a hint that it should look up the IP address of a given server. If the browser chooses to do so, this can speed up the loading of resources from that server.
#### Parameters[Link for Parameters]()
- `href`: a string. The URL of the server you want to connect to.
#### Returns[Link for Returns]()
`prefetchDNS` returns nothing.
#### Caveats[Link for Caveats]()
- Multiple calls to `prefetchDNS` with the same server have the same effect as a single call.
- In the browser, you can call `prefetchDNS` in any situation: while rendering a component, in an Effect, in an event handler, and so on.
- In server-side rendering or when rendering Server Components, `prefetchDNS` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored.
- If you know the specific resources you’ll need, you can call [other functions](https://react.dev/reference/react-dom) instead that will start loading the resources right away.
- There is no benefit to prefetching the same server the webpage itself is hosted from because it’s already been looked up by the time the hint would be given.
- Compared with [`preconnect`](https://react.dev/reference/react-dom/preconnect), `prefetchDNS` may be better if you are speculatively connecting to a large number of domains, in which case the overhead of preconnections might outweigh the benefit.
* * *
## Usage[Link for Usage]()
### Prefetching DNS when rendering[Link for Prefetching DNS when rendering]()
Call `prefetchDNS` when rendering a component if you know that its children will load external resources from that host.
```
import { prefetchDNS } from 'react-dom';
function AppRoot() {
prefetchDNS("https://example.com");
return ...;
}
```
### Prefetching DNS in an event handler[Link for Prefetching DNS in an event handler]()
Call `prefetchDNS` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state.
```
import { prefetchDNS } from 'react-dom';
function CallToAction() {
const onClick = () => {
prefetchDNS('http://example.com');
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}
```
[Previouspreconnect](https://react.dev/reference/react-dom/preconnect)
[Nextpreinit](https://react.dev/reference/react-dom/preinit) |
https://react.dev/reference/react-dom/createPortal | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# createPortal[Link for this heading]()
`createPortal` lets you render some children into a different part of the DOM.
```
<div>
<SomeComponent />
{createPortal(children, domNode, key?)}
</div>
```
- [Reference]()
- [`createPortal(children, domNode, key?)`]()
- [Usage]()
- [Rendering to a different part of the DOM]()
- [Rendering a modal dialog with a portal]()
- [Rendering React components into non-React server markup]()
- [Rendering React components into non-React DOM nodes]()
* * *
## Reference[Link for Reference]()
### `createPortal(children, domNode, key?)`[Link for this heading]()
To create a portal, call `createPortal`, passing some JSX, and the DOM node where it should be rendered:
```
import { createPortal } from 'react-dom';
// ...
<div>
<p>This child is placed in the parent div.</p>
{createPortal(
<p>This child is placed in the document body.</p>,
document.body
)}
</div>
```
[See more examples below.]()
A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events bubble up from children to parents according to the React tree.
#### Parameters[Link for Parameters]()
- `children`: Anything that can be rendered with React, such as a piece of JSX (e.g. `<div />` or `<SomeComponent />`), a [Fragment](https://react.dev/reference/react/Fragment) (`<>...</>`), a string or a number, or an array of these.
- `domNode`: Some DOM node, such as those returned by `document.getElementById()`. The node must already exist. Passing a different DOM node during an update will cause the portal content to be recreated.
- **optional** `key`: A unique string or number to be used as the portal’s [key.](https://react.dev/learn/rendering-lists)
#### Returns[Link for Returns]()
`createPortal` returns a React node that can be included into JSX or returned from a React component. If React encounters it in the render output, it will place the provided `children` inside the provided `domNode`.
#### Caveats[Link for Caveats]()
- Events from portals propagate according to the React tree rather than the DOM tree. For example, if you click inside a portal, and the portal is wrapped in `<div onClick>`, that `onClick` handler will fire. If this causes issues, either stop the event propagation from inside the portal, or move the portal itself up in the React tree.
* * *
## Usage[Link for Usage]()
### Rendering to a different part of the DOM[Link for Rendering to a different part of the DOM]()
*Portals* let your components render some of their children into a different place in the DOM. This lets a part of your component “escape” from whatever containers it may be in. For example, a component can display a modal dialog or a tooltip that appears above and outside of the rest of the page.
To create a portal, render the result of `createPortal` with some JSX and the DOM node where it should go:
```
import { createPortal } from 'react-dom';
function MyComponent() {
return (
<div style={{ border: '2px solid black' }}>
<p>This child is placed in the parent div.</p>
{createPortal(
<p>This child is placed in the document body.</p>,
document.body
)}
</div>
);
}
```
React will put the DOM nodes for the JSX you passed inside of the DOM node you provided.
Without a portal, the second `<p>` would be placed inside the parent `<div>`, but the portal “teleported” it into the [`document.body`:](https://developer.mozilla.org/en-US/docs/Web/API/Document/body)
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createPortal } from 'react-dom';
export default function MyComponent() {
return (
<div style={{ border: '2px solid black' }}>
<p>This child is placed in the parent div.</p>
{createPortal(
<p>This child is placed in the document body.</p>,
document.body
)}
</div>
);
}
```
Notice how the second paragraph visually appears outside the parent `<div>` with the border. If you inspect the DOM structure with developer tools, you’ll see that the second `<p>` got placed directly into the `<body>`:
```
<body>
<div id="root">
...
<div style="border: 2px solid black">
<p>This child is placed inside the parent div.</p>
</div>
...
</div>
<p>This child is placed in the document body.</p>
</body>
```
A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events still bubble up from children to parents according to the React tree.
* * *
### Rendering a modal dialog with a portal[Link for Rendering a modal dialog with a portal]()
You can use a portal to create a modal dialog that floats above the rest of the page, even if the component that summons the dialog is inside a container with `overflow: hidden` or other styles that interfere with the dialog.
In this example, the two containers have styles that disrupt the modal dialog, but the one rendered into a portal is unaffected because, in the DOM, the modal is not contained within the parent JSX elements.
App.jsNoPortalExample.jsPortalExample.jsModalContent.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import NoPortalExample from './NoPortalExample';
import PortalExample from './PortalExample';
export default function App() {
return (
<>
<div className="clipping-container">
<NoPortalExample />
</div>
<div className="clipping-container">
<PortalExample />
</div>
</>
);
}
```
### Pitfall
It’s important to make sure that your app is accessible when using portals. For instance, you may need to manage keyboard focus so that the user can move the focus in and out of the portal in a natural way.
Follow the [WAI-ARIA Modal Authoring Practices](https://www.w3.org/WAI/ARIA/apg/) when creating modals. If you use a community package, ensure that it is accessible and follows these guidelines.
* * *
### Rendering React components into non-React server markup[Link for Rendering React components into non-React server markup]()
Portals can be useful if your React root is only part of a static or server-rendered page that isn’t built with React. For example, if your page is built with a server framework like Rails, you can create areas of interactivity within static areas such as sidebars. Compared with having [multiple separate React roots,](https://react.dev/reference/react-dom/client/createRoot) portals let you treat the app as a single React tree with shared state even though its parts render to different parts of the DOM.
index.jsindex.htmlApp.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createPortal } from 'react-dom';
const sidebarContentEl = document.getElementById('sidebar-content');
export default function App() {
return (
<>
<MainContent />
{createPortal(
<SidebarContent />,
sidebarContentEl
)}
</>
);
}
function MainContent() {
return <p>This part is rendered by React</p>;
}
function SidebarContent() {
return <p>This part is also rendered by React!</p>;
}
```
Show more
* * *
### Rendering React components into non-React DOM nodes[Link for Rendering React components into non-React DOM nodes]()
You can also use a portal to manage the content of a DOM node that’s managed outside of React. For example, suppose you’re integrating with a non-React map widget and you want to render React content inside a popup. To do this, declare a `popupContainer` state variable to store the DOM node you’re going to render into:
```
const [popupContainer, setPopupContainer] = useState(null);
```
When you create the third-party widget, store the DOM node returned by the widget so you can render into it:
```
useEffect(() => {
if (mapRef.current === null) {
const map = createMapWidget(containerRef.current);
mapRef.current = map;
const popupDiv = addPopupToMapWidget(map);
setPopupContainer(popupDiv);
}
}, []);
```
This lets you use `createPortal` to render React content into `popupContainer` once it becomes available:
```
return (
<div style={{ width: 250, height: 250 }} ref={containerRef}>
{popupContainer !== null && createPortal(
<p>Hello from React!</p>,
popupContainer
)}
</div>
);
```
Here is a complete example you can play with:
App.jsmap-widget.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useRef, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { createMapWidget, addPopupToMapWidget } from './map-widget.js';
export default function Map() {
const containerRef = useRef(null);
const mapRef = useRef(null);
const [popupContainer, setPopupContainer] = useState(null);
useEffect(() => {
if (mapRef.current === null) {
const map = createMapWidget(containerRef.current);
mapRef.current = map;
const popupDiv = addPopupToMapWidget(map);
setPopupContainer(popupDiv);
}
}, []);
return (
<div style={{ width: 250, height: 250 }} ref={containerRef}>
{popupContainer !== null && createPortal(
<p>Hello from React!</p>,
popupContainer
)}
</div>
);
}
```
Show more
[PreviousAPIs](https://react.dev/reference/react-dom)
[NextflushSync](https://react.dev/reference/react-dom/flushSync) |
https://react.dev/reference/react-dom/preinit | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# preinit[Link for this heading]()
### Note
[React-based frameworks](https://react.dev/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework’s documentation for details.
`preinit` lets you eagerly fetch and evaluate a stylesheet or external script.
```
preinit("https://example.com/script.js", {as: "script"});
```
- [Reference]()
- [`preinit(href, options)`]()
- [Usage]()
- [Preiniting when rendering]()
- [Preiniting in an event handler]()
* * *
## Reference[Link for Reference]()
### `preinit(href, options)`[Link for this heading]()
To preinit a script or stylesheet, call the `preinit` function from `react-dom`.
```
import { preinit } from 'react-dom';
function AppRoot() {
preinit("https://example.com/script.js", {as: "script"});
// ...
}
```
[See more examples below.]()
The `preinit` function provides the browser with a hint that it should start downloading and executing the given resource, which can save time. Scripts that you `preinit` are executed when they finish downloading. Stylesheets that you preinit are inserted into the document, which causes them to go into effect right away.
#### Parameters[Link for Parameters]()
- `href`: a string. The URL of the resource you want to download and execute.
- `options`: an object. It contains the following properties:
- `as`: a required string. The type of resource. Its possible values are `script` and `style`.
- `precedence`: a string. Required with stylesheets. Says where to insert the stylesheet relative to others. Stylesheets with higher precedence can override those with lower precedence. The possible values are `reset`, `low`, `medium`, `high`.
- `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`. It is required when `as` is set to `"fetch"`.
- `integrity`: a string. A cryptographic hash of the resource, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
- `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
- `fetchPriority`: a string. Suggests a relative priority for fetching the resource. The possible values are `auto` (the default), `high`, and `low`.
#### Returns[Link for Returns]()
`preinit` returns nothing.
#### Caveats[Link for Caveats]()
- Multiple calls to `preinit` with the same `href` have the same effect as a single call.
- In the browser, you can call `preinit` in any situation: while rendering a component, in an Effect, in an event handler, and so on.
- In server-side rendering or when rendering Server Components, `preinit` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored.
* * *
## Usage[Link for Usage]()
### Preiniting when rendering[Link for Preiniting when rendering]()
Call `preinit` when rendering a component if you know that it or its children will use a specific resource, and you’re OK with the resource being evaluated and thereby taking effect immediately upon being downloaded.
#### Examples of preiniting[Link for Examples of preiniting]()
1\. Preiniting an external script 2. Preiniting a stylesheet
#### Example 1 of 2: Preiniting an external script[Link for this heading]()
```
import { preinit } from 'react-dom';
function AppRoot() {
preinit("https://example.com/script.js", {as: "script"});
return ...;
}
```
If you want the browser to download the script but not to execute it right away, use [`preload`](https://react.dev/reference/react-dom/preload) instead. If you want to load an ESM module, use [`preinitModule`](https://react.dev/reference/react-dom/preinitModule).
Next Example
### Preiniting in an event handler[Link for Preiniting in an event handler]()
Call `preinit` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state.
```
import { preinit } from 'react-dom';
function CallToAction() {
const onClick = () => {
preinit("https://example.com/wizardStyles.css", {as: "style"});
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}
```
[PreviousprefetchDNS](https://react.dev/reference/react-dom/prefetchDNS)
[NextpreinitModule](https://react.dev/reference/react-dom/preinitModule) |
https://react.dev/reference/react-dom/preloadModule | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# preloadModule[Link for this heading]()
### Note
[React-based frameworks](https://react.dev/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework’s documentation for details.
`preloadModule` lets you eagerly fetch an ESM module that you expect to use.
```
preloadModule("https://example.com/module.js", {as: "script"});
```
- [Reference]()
- [`preloadModule(href, options)`]()
- [Usage]()
- [Preloading when rendering]()
- [Preloading in an event handler]()
* * *
## Reference[Link for Reference]()
### `preloadModule(href, options)`[Link for this heading]()
To preload an ESM module, call the `preloadModule` function from `react-dom`.
```
import { preloadModule } from 'react-dom';
function AppRoot() {
preloadModule("https://example.com/module.js", {as: "script"});
// ...
}
```
[See more examples below.]()
The `preloadModule` function provides the browser with a hint that it should start downloading the given module, which can save time.
#### Parameters[Link for Parameters]()
- `href`: a string. The URL of the module you want to download.
- `options`: an object. It contains the following properties:
- `as`: a required string. It must be `'script'`.
- `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`.
- `integrity`: a string. A cryptographic hash of the module, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
- `nonce`: a string. A cryptographic [nonce to allow the module](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
#### Returns[Link for Returns]()
`preloadModule` returns nothing.
#### Caveats[Link for Caveats]()
- Multiple calls to `preloadModule` with the same `href` have the same effect as a single call.
- In the browser, you can call `preloadModule` in any situation: while rendering a component, in an Effect, in an event handler, and so on.
- In server-side rendering or when rendering Server Components, `preloadModule` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored.
* * *
## Usage[Link for Usage]()
### Preloading when rendering[Link for Preloading when rendering]()
Call `preloadModule` when rendering a component if you know that it or its children will use a specific module.
```
import { preloadModule } from 'react-dom';
function AppRoot() {
preloadModule("https://example.com/module.js", {as: "script"});
return ...;
}
```
If you want the browser to start executing the module immediately (rather than just downloading it), use [`preinitModule`](https://react.dev/reference/react-dom/preinitModule) instead. If you want to load a script that isn’t an ESM module, use [`preload`](https://react.dev/reference/react-dom/preload).
### Preloading in an event handler[Link for Preloading in an event handler]()
Call `preloadModule` in an event handler before transitioning to a page or state where the module will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state.
```
import { preloadModule } from 'react-dom';
function CallToAction() {
const onClick = () => {
preloadModule("https://example.com/module.js", {as: "script"});
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}
```
[Previouspreload](https://react.dev/reference/react-dom/preload)
[NextClient APIs](https://react.dev/reference/react-dom/client) |
https://react.dev/reference/react-dom/preinitModule | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# preinitModule[Link for this heading]()
### Note
[React-based frameworks](https://react.dev/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework’s documentation for details.
`preinitModule` lets you eagerly fetch and evaluate an ESM module.
```
preinitModule("https://example.com/module.js", {as: "script"});
```
- [Reference]()
- [`preinitModule(href, options)`]()
- [Usage]()
- [Preloading when rendering]()
- [Preloading in an event handler]()
* * *
## Reference[Link for Reference]()
### `preinitModule(href, options)`[Link for this heading]()
To preinit an ESM module, call the `preinitModule` function from `react-dom`.
```
import { preinitModule } from 'react-dom';
function AppRoot() {
preinitModule("https://example.com/module.js", {as: "script"});
// ...
}
```
[See more examples below.]()
The `preinitModule` function provides the browser with a hint that it should start downloading and executing the given module, which can save time. Modules that you `preinit` are executed when they finish downloading.
#### Parameters[Link for Parameters]()
- `href`: a string. The URL of the module you want to download and execute.
- `options`: an object. It contains the following properties:
- `as`: a required string. It must be `'script'`.
- `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`.
- `integrity`: a string. A cryptographic hash of the module, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
- `nonce`: a string. A cryptographic [nonce to allow the module](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
#### Returns[Link for Returns]()
`preinitModule` returns nothing.
#### Caveats[Link for Caveats]()
- Multiple calls to `preinitModule` with the same `href` have the same effect as a single call.
- In the browser, you can call `preinitModule` in any situation: while rendering a component, in an Effect, in an event handler, and so on.
- In server-side rendering or when rendering Server Components, `preinitModule` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored.
* * *
## Usage[Link for Usage]()
### Preloading when rendering[Link for Preloading when rendering]()
Call `preinitModule` when rendering a component if you know that it or its children will use a specific module and you’re OK with the module being evaluated and thereby taking effect immediately upon being downloaded.
```
import { preinitModule } from 'react-dom';
function AppRoot() {
preinitModule("https://example.com/module.js", {as: "script"});
return ...;
}
```
If you want the browser to download the module but not to execute it right away, use [`preloadModule`](https://react.dev/reference/react-dom/preloadModule) instead. If you want to preinit a script that isn’t an ESM module, use [`preinit`](https://react.dev/reference/react-dom/preinit).
### Preloading in an event handler[Link for Preloading in an event handler]()
Call `preinitModule` in an event handler before transitioning to a page or state where the module will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state.
```
import { preinitModule } from 'react-dom';
function CallToAction() {
const onClick = () => {
preinitModule("https://example.com/module.js", {as: "script"});
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}
```
[Previouspreinit](https://react.dev/reference/react-dom/preinit)
[Nextpreload](https://react.dev/reference/react-dom/preload) |
https://react.dev/reference/react-dom/preload | [API Reference](https://react.dev/reference/react)
[APIs](https://react.dev/reference/react-dom)
# preload[Link for this heading]()
### Note
[React-based frameworks](https://react.dev/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework’s documentation for details.
`preload` lets you eagerly fetch a resource such as a stylesheet, font, or external script that you expect to use.
```
preload("https://example.com/font.woff2", {as: "font"});
```
- [Reference]()
- [`preload(href, options)`]()
- [Usage]()
- [Preloading when rendering]()
- [Preloading in an event handler]()
* * *
## Reference[Link for Reference]()
### `preload(href, options)`[Link for this heading]()
To preload a resource, call the `preload` function from `react-dom`.
```
import { preload } from 'react-dom';
function AppRoot() {
preload("https://example.com/font.woff2", {as: "font"});
// ...
}
```
[See more examples below.]()
The `preload` function provides the browser with a hint that it should start downloading the given resource, which can save time.
#### Parameters[Link for Parameters]()
- `href`: a string. The URL of the resource you want to download.
- `options`: an object. It contains the following properties:
- `as`: a required string. The type of resource. Its [possible values](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) are `audio`, `document`, `embed`, `fetch`, `font`, `image`, `object`, `script`, `style`, `track`, `video`, `worker`.
- `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`. It is required when `as` is set to `"fetch"`.
- `referrerPolicy`: a string. The [Referrer header](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) to send when fetching. Its possible values are `no-referrer-when-downgrade` (the default), `no-referrer`, `origin`, `origin-when-cross-origin`, and `unsafe-url`.
- `integrity`: a string. A cryptographic hash of the resource, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
- `type`: a string. The MIME type of the resource.
- `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
- `fetchPriority`: a string. Suggests a relative priority for fetching the resource. The possible values are `auto` (the default), `high`, and `low`.
- `imageSrcSet`: a string. For use only with `as: "image"`. Specifies the [source set of the image](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).
- `imageSizes`: a string. For use only with `as: "image"`. Specifies the [sizes of the image](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).
#### Returns[Link for Returns]()
`preload` returns nothing.
#### Caveats[Link for Caveats]()
- Multiple equivalent calls to `preload` have the same effect as a single call. Calls to `preload` are considered equivalent according to the following rules:
- Two calls are equivalent if they have the same `href`, except:
- If `as` is set to `image`, two calls are equivalent if they have the same `href`, `imageSrcSet`, and `imageSizes`.
- In the browser, you can call `preload` in any situation: while rendering a component, in an Effect, in an event handler, and so on.
- In server-side rendering or when rendering Server Components, `preload` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored.
* * *
## Usage[Link for Usage]()
### Preloading when rendering[Link for Preloading when rendering]()
Call `preload` when rendering a component if you know that it or its children will use a specific resource.
#### Examples of preloading[Link for Examples of preloading]()
1\. Preloading an external script 2. Preloading a stylesheet 3. Preloading a font 4. Preloading an image
#### Example 1 of 4: Preloading an external script[Link for this heading]()
```
import { preload } from 'react-dom';
function AppRoot() {
preload("https://example.com/script.js", {as: "script"});
return ...;
}
```
If you want the browser to start executing the script immediately (rather than just downloading it), use [`preinit`](https://react.dev/reference/react-dom/preinit) instead. If you want to load an ESM module, use [`preloadModule`](https://react.dev/reference/react-dom/preloadModule).
Next Example
### Preloading in an event handler[Link for Preloading in an event handler]()
Call `preload` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state.
```
import { preload } from 'react-dom';
function CallToAction() {
const onClick = () => {
preload("https://example.com/wizardStyles.css", {as: "style"});
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}
```
[PreviouspreinitModule](https://react.dev/reference/react-dom/preinitModule)
[NextpreloadModule](https://react.dev/reference/react-dom/preloadModule) |
https://react.dev/reference/react-dom/client | [API Reference](https://react.dev/reference/react)
# Client React DOM APIs[Link for this heading]()
The `react-dom/client` APIs let you render React components on the client (in the browser). These APIs are typically used at the top level of your app to initialize your React tree. A [framework](https://react.dev/learn/start-a-new-react-project) may call them for you. Most of your components don’t need to import or use them.
* * *
## Client APIs[Link for Client APIs]()
- [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) lets you create a root to display React components inside a browser DOM node.
- [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](https://react.dev/reference/react-dom/server)
* * *
## Browser support[Link for Browser support]()
React supports all popular browsers, including Internet Explorer 9 and above. Some polyfills are required for older browsers such as IE 9 and IE 10.
[PreviouspreloadModule](https://react.dev/reference/react-dom/preloadModule)
[NextcreateRoot](https://react.dev/reference/react-dom/client/createRoot) |
https://react.dev/reference/react-dom/server | [API Reference](https://react.dev/reference/react)
# Server React DOM APIs[Link for this heading]()
The `react-dom/server` APIs let you server-side render React components to HTML. These APIs are only used on the server at the top level of your app to generate the initial HTML. A [framework](https://react.dev/learn/start-a-new-react-project) may call them for you. Most of your components don’t need to import or use them.
* * *
## Server APIs for Node.js Streams[Link for Server APIs for Node.js Streams]()
These methods are only available in the environments with [Node.js Streams:](https://nodejs.org/api/stream.html)
- [`renderToPipeableStream`](https://react.dev/reference/react-dom/server/renderToPipeableStream) renders a React tree to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html)
* * *
## Server APIs for Web Streams[Link for Server APIs for Web Streams]()
These methods are only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), which includes browsers, Deno, and some modern edge runtimes:
- [`renderToReadableStream`](https://react.dev/reference/react-dom/server/renderToReadableStream) renders a React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
* * *
## Legacy Server APIs for non-streaming environments[Link for Legacy Server APIs for non-streaming environments]()
These methods can be used in the environments that don’t support streams:
- [`renderToString`](https://react.dev/reference/react-dom/server/renderToString) renders a React tree to a string.
- [`renderToStaticMarkup`](https://react.dev/reference/react-dom/server/renderToStaticMarkup) renders a non-interactive React tree to a string.
They have limited functionality compared to the streaming APIs.
[PrevioushydrateRoot](https://react.dev/reference/react-dom/client/hydrateRoot)
[NextrenderToPipeableStream](https://react.dev/reference/react-dom/server/renderToPipeableStream) |
https://react.dev/reference/react-dom/client/createRoot | [API Reference](https://react.dev/reference/react)
[Client APIs](https://react.dev/reference/react-dom/client)
# createRoot[Link for this heading]()
`createRoot` lets you create a root to display React components inside a browser DOM node.
```
const root = createRoot(domNode, options?)
```
- [Reference]()
- [`createRoot(domNode, options?)`]()
- [`root.render(reactNode)`]()
- [`root.unmount()`]()
- [Usage]()
- [Rendering an app fully built with React]()
- [Rendering a page partially built with React]()
- [Updating a root component]()
- [Show a dialog for uncaught errors]()
- [Displaying Error Boundary errors]()
- [Displaying a dialog for recoverable errors]()
- [Troubleshooting]()
- [I’ve created a root, but nothing is displayed]()
- [I’m getting an error: “You passed a second argument to root.render”]()
- [I’m getting an error: “Target container is not a DOM element”]()
- [I’m getting an error: “Functions are not valid as a React child.”]()
- [My server-rendered HTML gets re-created from scratch]()
* * *
## Reference[Link for Reference]()
### `createRoot(domNode, options?)`[Link for this heading]()
Call `createRoot` to create a React root for displaying content inside a browser DOM element.
```
import { createRoot } from 'react-dom/client';
const domNode = document.getElementById('root');
const root = createRoot(domNode);
```
React will create a root for the `domNode`, and take over managing the DOM inside it. After you’ve created a root, you need to call [`root.render`]() to display a React component inside of it:
```
root.render(<App />);
```
An app fully built with React will usually only have one `createRoot` call for its root component. A page that uses “sprinkles” of React for parts of the page may have as many separate roots as needed.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will create a root for this DOM element and allow you to call functions on the root, such as `render` to display rendered React content.
- **optional** `options`: An object with options for this React root.
- **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`.
- **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown, and an `errorInfo` object containing the `componentStack`.
- **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with an `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`.
- **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](https://react.dev/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page.
#### Returns[Link for Returns]()
`createRoot` returns an object with two methods: [`render`]() and [`unmount`.]()
#### Caveats[Link for Caveats]()
- If your app is server-rendered, using `createRoot()` is not supported. Use [`hydrateRoot()`](https://react.dev/reference/react-dom/client/hydrateRoot) instead.
- You’ll likely have only one `createRoot` call in your app. If you use a framework, it might do this call for you.
- When you want to render a piece of JSX in a different part of the DOM tree that isn’t a child of your component (for example, a modal or a tooltip), use [`createPortal`](https://react.dev/reference/react-dom/createPortal) instead of `createRoot`.
* * *
### `root.render(reactNode)`[Link for this heading]()
Call `root.render` to display a piece of [JSX](https://react.dev/learn/writing-markup-with-jsx) (“React node”) into the React root’s browser DOM node.
```
root.render(<App />);
```
React will display `<App />` in the `root`, and take over managing the DOM inside it.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `reactNode`: A *React node* that you want to display. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](https://react.dev/reference/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns[Link for Returns]()
`root.render` returns `undefined`.
#### Caveats[Link for Caveats]()
- The first time you call `root.render`, React will clear all the existing HTML content inside the React root before rendering the React component into it.
- If your root’s DOM node contains HTML generated by React on the server or during the build, use [`hydrateRoot()`](https://react.dev/reference/react-dom/client/hydrateRoot) instead, which attaches the event handlers to the existing HTML.
- If you call `render` on the same root more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by [“matching it up”](https://react.dev/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` on the same root again is similar to calling the [`set` function](https://react.dev/reference/react/useState) on the root component: React avoids unnecessary DOM updates.
* * *
### `root.unmount()`[Link for this heading]()
Call `root.unmount` to destroy a rendered tree inside a React root.
```
root.unmount();
```
An app fully built with React will usually not have any calls to `root.unmount`.
This is mostly useful if your React root’s DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to “stop” managing the removed root’s content by calling `root.unmount`. Otherwise, the components inside the removed root won’t know to clean up and free up global resources like subscriptions.
Calling `root.unmount` will unmount all the components in the root and “detach” React from the root DOM node, including removing any event handlers or state in the tree.
#### Parameters[Link for Parameters]()
`root.unmount` does not accept any parameters.
#### Returns[Link for Returns]()
`root.unmount` returns `undefined`.
#### Caveats[Link for Caveats]()
- Calling `root.unmount` will unmount all the components in the tree and “detach” React from the root DOM node.
- Once you call `root.unmount` you cannot call `root.render` again on the same root. Attempting to call `root.render` on an unmounted root will throw a “Cannot update an unmounted root” error. However, you can create a new root for the same DOM node after the previous root for that node has been unmounted.
* * *
## Usage[Link for Usage]()
### Rendering an app fully built with React[Link for Rendering an app fully built with React]()
If your app is fully built with React, create a single root for your entire app.
```
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
```
Usually, you only need to run this code once at startup. It will:
1. Find the browser DOM node defined in your HTML.
2. Display the React component for your app inside.
index.jsindex.htmlApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
```
**If your app is fully built with React, you shouldn’t need to create any more roots, or to call [`root.render`]() again.**
From this point on, React will manage the DOM of your entire app. To add more components, [nest them inside the `App` component.](https://react.dev/learn/importing-and-exporting-components) When you need to update the UI, each of your components can do this by [using state.](https://react.dev/reference/react/useState) When you need to display extra content like a modal or a tooltip outside the DOM node, [render it with a portal.](https://react.dev/reference/react-dom/createPortal)
### Note
When your HTML is empty, the user sees a blank page until the app’s JavaScript code loads and runs:
```
<div id="root"></div>
```
This can feel very slow! To solve this, you can generate the initial HTML from your components [on the server or during the build.](https://react.dev/reference/react-dom/server) Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend [using a framework](https://react.dev/learn/start-a-new-react-project) that does this optimization out of the box. Depending on when it runs, this is called *server-side rendering (SSR)* or *static site generation (SSG).*
### Pitfall
**Apps using server rendering or static generation must call [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) instead of `createRoot`.** React will then *hydrate* (reuse) the DOM nodes from your HTML instead of destroying and re-creating them.
* * *
### Rendering a page partially built with React[Link for Rendering a page partially built with React]()
If your page [isn’t fully built with React](https://react.dev/learn/add-react-to-an-existing-project), you can call `createRoot` multiple times to create a root for each top-level piece of UI managed by React. You can display different content in each root by calling [`root.render`.]()
Here, two different React components are rendered into two DOM nodes defined in the `index.html` file:
index.jsindex.htmlComponents.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import './styles.css';
import { createRoot } from 'react-dom/client';
import { Comments, Navigation } from './Components.js';
const navDomNode = document.getElementById('navigation');
const navRoot = createRoot(navDomNode);
navRoot.render(<Navigation />);
const commentDomNode = document.getElementById('comments');
const commentRoot = createRoot(commentDomNode);
commentRoot.render(<Comments />);
```
You could also create a new DOM node with [`document.createElement()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) and add it to the document manually.
```
const domNode = document.createElement('div');
const root = createRoot(domNode);
root.render(<Comment />);
document.body.appendChild(domNode); // You can add it anywhere in the document
```
To remove the React tree from the DOM node and clean up all the resources used by it, call [`root.unmount`.]()
```
root.unmount();
```
This is mostly useful if your React components are inside an app written in a different framework.
* * *
### Updating a root component[Link for Updating a root component]()
You can call `render` more than once on the same root. As long as the component tree structure matches up with what was previously rendered, React will [preserve the state.](https://react.dev/learn/preserving-and-resetting-state) Notice how you can type in the input, which means that the updates from repeated `render` calls every second in this example are not destructive:
index.jsApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from 'react-dom/client';
import './styles.css';
import App from './App.js';
const root = createRoot(document.getElementById('root'));
let i = 0;
setInterval(() => {
root.render(<App counter={i} />);
i++;
}, 1000);
```
It is uncommon to call `render` multiple times. Usually, your components will [update state](https://react.dev/reference/react/useState) instead.
### Show a dialog for uncaught errors[Link for Show a dialog for uncaught errors]()
By default, React will log all uncaught errors to the console. To implement your own error reporting, you can provide the optional `onUncaughtError` root option:
```
import { createRoot } from 'react-dom/client';
const root = createRoot(
document.getElementById('root'),
{
onUncaughtError: (error, errorInfo) => {
console.error(
'Uncaught error',
error,
errorInfo.componentStack
);
}
}
);
root.render(<App />);
```
The onUncaughtError option is a function called with two arguments:
1. The error that was thrown.
2. An errorInfo object that contains the componentStack of the error.
You can use the `onUncaughtError` root option to display error dialogs:
index.jsApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from "react-dom/client";
import App from "./App.js";
import {reportUncaughtError} from "./reportError";
import "./styles.css";
const container = document.getElementById("root");
const root = createRoot(container, {
onUncaughtError: (error, errorInfo) => {
if (error.message !== 'Known error') {
reportUncaughtError({
error,
componentStack: errorInfo.componentStack
});
}
}
});
root.render(<App />);
```
Show more
### Displaying Error Boundary errors[Link for Displaying Error Boundary errors]()
By default, React will log all errors caught by an Error Boundary to `console.error`. To override this behavior, you can provide the optional `onCaughtError` root option to handle errors caught by an [Error Boundary](https://react.dev/reference/react/Component):
```
import { createRoot } from 'react-dom/client';
const root = createRoot(
document.getElementById('root'),
{
onCaughtError: (error, errorInfo) => {
console.error(
'Caught error',
error,
errorInfo.componentStack
);
}
}
);
root.render(<App />);
```
The onCaughtError option is a function called with two arguments:
1. The error that was caught by the boundary.
2. An errorInfo object that contains the componentStack of the error.
You can use the `onCaughtError` root option to display error dialogs or filter known errors from logging:
index.jsApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from "react-dom/client";
import App from "./App.js";
import {reportCaughtError} from "./reportError";
import "./styles.css";
const container = document.getElementById("root");
const root = createRoot(container, {
onCaughtError: (error, errorInfo) => {
if (error.message !== 'Known error') {
reportCaughtError({
error,
componentStack: errorInfo.componentStack,
});
}
}
});
root.render(<App />);
```
Show more
### Displaying a dialog for recoverable errors[Link for Displaying a dialog for recoverable errors]()
React may automatically render a component a second time to attempt to recover from an error thrown in render. If successful, React will log a recoverable error to the console to notify the developer. To override this behavior, you can provide the optional `onRecoverableError` root option:
```
import { createRoot } from 'react-dom/client';
const root = createRoot(
document.getElementById('root'),
{
onRecoverableError: (error, errorInfo) => {
console.error(
'Recoverable error',
error,
error.cause,
errorInfo.componentStack,
);
}
}
);
root.render(<App />);
```
The onRecoverableError option is a function called with two arguments:
1. The error that React throws. Some errors may include the original cause as error.cause.
2. An errorInfo object that contains the componentStack of the error.
You can use the `onRecoverableError` root option to display error dialogs:
index.jsApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { createRoot } from "react-dom/client";
import App from "./App.js";
import {reportRecoverableError} from "./reportError";
import "./styles.css";
const container = document.getElementById("root");
const root = createRoot(container, {
onRecoverableError: (error, errorInfo) => {
reportRecoverableError({
error,
cause: error.cause,
componentStack: errorInfo.componentStack,
});
}
});
root.render(<App />);
```
Show more
* * *
## Troubleshooting[Link for Troubleshooting]()
### I’ve created a root, but nothing is displayed[Link for I’ve created a root, but nothing is displayed]()
Make sure you haven’t forgotten to actually *render* your app into the root:
```
import { createRoot } from 'react-dom/client';
import App from './App.js';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
```
Until you do that, nothing is displayed.
* * *
### I’m getting an error: “You passed a second argument to root.render”[Link for I’m getting an error: “You passed a second argument to root.render”]()
A common mistake is to pass the options for `createRoot` to `root.render(...)`:
Console
Warning: You passed a second argument to root.render(…) but it only accepts one argument.
To fix, pass the root options to `createRoot(...)`, not `root.render(...)`:
```
// 🚩 Wrong: root.render only takes one argument.
root.render(App, {onUncaughtError});
// ✅ Correct: pass options to createRoot.
const root = createRoot(container, {onUncaughtError});
root.render(<App />);
```
* * *
### I’m getting an error: “Target container is not a DOM element”[Link for I’m getting an error: “Target container is not a DOM element”]()
This error means that whatever you’re passing to `createRoot` is not a DOM node.
If you’re not sure what’s happening, try logging it:
```
const domNode = document.getElementById('root');
console.log(domNode); // ???
const root = createRoot(domNode);
root.render(<App />);
```
For example, if `domNode` is `null`, it means that [`getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) returned `null`. This will happen if there is no node in the document with the given ID at the time of your call. There may be a few reasons for it:
1. The ID you’re looking for might differ from the ID you used in the HTML file. Check for typos!
2. Your bundle’s `<script>` tag cannot “see” any DOM nodes that appear *after* it in the HTML.
Another common way to get this error is to write `createRoot(<App />)` instead of `createRoot(domNode)`.
* * *
### I’m getting an error: “Functions are not valid as a React child.”[Link for I’m getting an error: “Functions are not valid as a React child.”]()
This error means that whatever you’re passing to `root.render` is not a React component.
This may happen if you call `root.render` with `Component` instead of `<Component />`:
```
// 🚩 Wrong: App is a function, not a Component.
root.render(App);
// ✅ Correct: <App /> is a component.
root.render(<App />);
```
Or if you pass a function to `root.render`, instead of the result of calling it:
```
// 🚩 Wrong: createApp is a function, not a component.
root.render(createApp);
// ✅ Correct: call createApp to return a component.
root.render(createApp());
```
* * *
### My server-rendered HTML gets re-created from scratch[Link for My server-rendered HTML gets re-created from scratch]()
If your app is server-rendered and includes the initial HTML generated by React, you might notice that creating a root and calling `root.render` deletes all that HTML, and then re-creates all the DOM nodes from scratch. This can be slower, resets focus and scroll positions, and may lose other user input.
Server-rendered apps must use [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) instead of `createRoot`:
```
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(
document.getElementById('root'),
<App />
);
```
Note that its API is different. In particular, usually there will be no further `root.render` call.
[PreviousClient APIs](https://react.dev/reference/react-dom/client)
[NexthydrateRoot](https://react.dev/reference/react-dom/client/hydrateRoot) |
https://react.dev/reference/react-dom/client/hydrateRoot | [API Reference](https://react.dev/reference/react)
[Client APIs](https://react.dev/reference/react-dom/client)
# hydrateRoot[Link for this heading]()
`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](https://react.dev/reference/react-dom/server)
```
const root = hydrateRoot(domNode, reactNode, options?)
```
- [Reference]()
- [`hydrateRoot(domNode, reactNode, options?)`]()
- [`root.render(reactNode)`]()
- [`root.unmount()`]()
- [Usage]()
- [Hydrating server-rendered HTML]()
- [Hydrating an entire document]()
- [Suppressing unavoidable hydration mismatch errors]()
- [Handling different client and server content]()
- [Updating a hydrated root component]()
- [Show a dialog for uncaught errors]()
- [Displaying Error Boundary errors]()
- [Show a dialog for recoverable hydration mismatch errors]()
- [Troubleshooting]()
- [I’m getting an error: “You passed a second argument to root.render”]()
* * *
## Reference[Link for Reference]()
### `hydrateRoot(domNode, reactNode, options?)`[Link for this heading]()
Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment.
```
import { hydrateRoot } from 'react-dom/client';
const domNode = document.getElementById('root');
const root = hydrateRoot(domNode, reactNode);
```
React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrateRoot` call with its root component.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
- `reactNode`: The “React node” used to render the existing HTML. This will usually be a piece of JSX like `<App />` which was rendered with a `ReactDOM Server` method such as `renderToPipeableStream(<App />)`.
- **optional** `options`: An object with options for this React root.
- **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`.
- **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown and an `errorInfo` object containing the `componentStack`.
- **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with the `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`.
- **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](https://react.dev/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server.
#### Returns[Link for Returns]()
`hydrateRoot` returns an object with two methods: [`render`]() and [`unmount`.]()
#### Caveats[Link for Caveats]()
- `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them.
- In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
- You’ll likely have only one `hydrateRoot` call in your app. If you use a framework, it might do this call for you.
- If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](https://react.dev/reference/react-dom/client/createRoot) instead.
* * *
### `root.render(reactNode)`[Link for this heading]()
Call `root.render` to update a React component inside a hydrated React root for a browser DOM element.
```
root.render(<App />);
```
React will update `<App />` in the hydrated `root`.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `reactNode`: A “React node” that you want to update. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](https://react.dev/reference/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns[Link for Returns]()
`root.render` returns `undefined`.
#### Caveats[Link for Caveats]()
- If you call `root.render` before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering.
* * *
### `root.unmount()`[Link for this heading]()
Call `root.unmount` to destroy a rendered tree inside a React root.
```
root.unmount();
```
An app fully built with React will usually not have any calls to `root.unmount`.
This is mostly useful if your React root’s DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. You need to tell React to “stop” managing the removed root’s content by calling `root.unmount`. Otherwise, the components inside the removed root won’t clean up and free up resources like subscriptions.
Calling `root.unmount` will unmount all the components in the root and “detach” React from the root DOM node, including removing any event handlers or state in the tree.
#### Parameters[Link for Parameters]()
`root.unmount` does not accept any parameters.
#### Returns[Link for Returns]()
`root.unmount` returns `undefined`.
#### Caveats[Link for Caveats]()
- Calling `root.unmount` will unmount all the components in the tree and “detach” React from the root DOM node.
- Once you call `root.unmount` you cannot call `root.render` again on the root. Attempting to call `root.render` on an unmounted root will throw a “Cannot update an unmounted root” error.
* * *
## Usage[Link for Usage]()
### Hydrating server-rendered HTML[Link for Hydrating server-rendered HTML]()
If your app’s HTML was generated by [`react-dom/server`](https://react.dev/reference/react-dom/client/createRoot), you need to *hydrate* it on the client.
```
import { hydrateRoot } from 'react-dom/client';
hydrateRoot(document.getElementById('root'), <App />);
```
This will hydrate the server HTML inside the browser DOM node with the React component for your app. Usually, you will do it once at startup. If you use a framework, it might do this behind the scenes for you.
To hydrate your app, React will “attach” your components’ logic to the initial generated HTML from the server. Hydration turns the initial HTML snapshot from the server into a fully interactive app that runs in the browser.
index.jsindex.htmlApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import './styles.css';
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(
document.getElementById('root'),
<App />
);
```
You shouldn’t need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. To update the UI, your components will [use state](https://react.dev/reference/react/useState) instead.
### Pitfall
The React tree you pass to `hydrateRoot` needs to produce **the same output** as it did on the server.
This is important for the user experience. The user will spend some time looking at the server-generated HTML before your JavaScript code loads. Server rendering creates an illusion that the app loads faster by showing the HTML snapshot of its output. Suddenly showing different content breaks that illusion. This is why the server render output must match the initial render output on the client.
The most common causes leading to hydration errors include:
- Extra whitespace (like newlines) around the React-generated HTML inside the root node.
- Using checks like `typeof window !== 'undefined'` in your rendering logic.
- Using browser-only APIs like [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in your rendering logic.
- Rendering different data on the server and the client.
React recovers from some hydration errors, but **you must fix them like other bugs.** In the best case, they’ll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.
* * *
### Hydrating an entire document[Link for Hydrating an entire document]()
Apps fully built with React can render the entire document as JSX, including the [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) tag:
```
function App() {
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/styles.css"></link>
<title>My app</title>
</head>
<body>
<Router />
</body>
</html>
);
}
```
To hydrate the entire document, pass the [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) global as the first argument to `hydrateRoot`:
```
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);
```
* * *
### Suppressing unavoidable hydration mismatch errors[Link for Suppressing unavoidable hydration mismatch errors]()
If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the hydration mismatch warning.
To silence hydration warnings on an element, add `suppressHydrationWarning={true}`:
index.jsindex.htmlApp.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
export default function App() {
return (
<h1 suppressHydrationWarning={true}>
Current Date: {new Date().toLocaleDateString()}
</h1>
);
}
```
This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates.
* * *
### Handling different client and server content[Link for Handling different client and server content]()
If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](https://react.dev/reference/react/useState) like `isClient`, which you can set to `true` in an [Effect](https://react.dev/reference/react/useEffect):
index.jsindex.htmlApp.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState, useEffect } from "react";
export default function App() {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
return (
<h1>
{isClient ? 'Is Client' : 'Is Server'}
</h1>
);
}
```
This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration.
### Pitfall
This approach makes hydration slower because your components have to render twice. Be mindful of the user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so rendering a different UI immediately after hydration may also feel jarring to the user.
* * *
### Updating a hydrated root component[Link for Updating a hydrated root component]()
After the root has finished hydrating, you can call [`root.render`]() to update the root React component. **Unlike with [`createRoot`](https://react.dev/reference/react-dom/client/createRoot), you don’t usually need to do this because the initial content was already rendered as HTML.**
If you call `root.render` at some point after hydration, and the component tree structure matches up with what was previously rendered, React will [preserve the state.](https://react.dev/learn/preserving-and-resetting-state) Notice how you can type in the input, which means that the updates from repeated `render` calls every second in this example are not destructive:
index.jsindex.htmlApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { hydrateRoot } from 'react-dom/client';
import './styles.css';
import App from './App.js';
const root = hydrateRoot(
document.getElementById('root'),
<App counter={0} />
);
let i = 0;
setInterval(() => {
root.render(<App counter={i} />);
i++;
}, 1000);
```
It is uncommon to call [`root.render`]() on a hydrated root. Usually, you’ll [update state](https://react.dev/reference/react/useState) inside one of the components instead.
### Show a dialog for uncaught errors[Link for Show a dialog for uncaught errors]()
By default, React will log all uncaught errors to the console. To implement your own error reporting, you can provide the optional `onUncaughtError` root option:
```
import { hydrateRoot } from 'react-dom/client';
const root = hydrateRoot(
document.getElementById('root'),
<App />,
{
onUncaughtError: (error, errorInfo) => {
console.error(
'Uncaught error',
error,
errorInfo.componentStack
);
}
}
);
root.render(<App />);
```
The onUncaughtError option is a function called with two arguments:
1. The error that was thrown.
2. An errorInfo object that contains the componentStack of the error.
You can use the `onUncaughtError` root option to display error dialogs:
index.jsApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
import {reportUncaughtError} from "./reportError";
import "./styles.css";
import {renderToString} from 'react-dom/server';
const container = document.getElementById("root");
const root = hydrateRoot(container, <App />, {
onUncaughtError: (error, errorInfo) => {
if (error.message !== 'Known error') {
reportUncaughtError({
error,
componentStack: errorInfo.componentStack
});
}
}
});
```
Show more
### Displaying Error Boundary errors[Link for Displaying Error Boundary errors]()
By default, React will log all errors caught by an Error Boundary to `console.error`. To override this behavior, you can provide the optional `onCaughtError` root option for errors caught by an [Error Boundary](https://react.dev/reference/react/Component):
```
import { hydrateRoot } from 'react-dom/client';
const root = hydrateRoot(
document.getElementById('root'),
<App />,
{
onCaughtError: (error, errorInfo) => {
console.error(
'Caught error',
error,
errorInfo.componentStack
);
}
}
);
root.render(<App />);
```
The onCaughtError option is a function called with two arguments:
1. The error that was caught by the boundary.
2. An errorInfo object that contains the componentStack of the error.
You can use the `onCaughtError` root option to display error dialogs or filter known errors from logging:
index.jsApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
import {reportCaughtError} from "./reportError";
import "./styles.css";
const container = document.getElementById("root");
const root = hydrateRoot(container, <App />, {
onCaughtError: (error, errorInfo) => {
if (error.message !== 'Known error') {
reportCaughtError({
error,
componentStack: errorInfo.componentStack
});
}
}
});
```
Show more
### Show a dialog for recoverable hydration mismatch errors[Link for Show a dialog for recoverable hydration mismatch errors]()
When React encounters a hydration mismatch, it will automatically attempt to recover by rendering on the client. By default, React will log hydration mismatch errors to `console.error`. To override this behavior, you can provide the optional `onRecoverableError` root option:
```
import { hydrateRoot } from 'react-dom/client';
const root = hydrateRoot(
document.getElementById('root'),
<App />,
{
onRecoverableError: (error, errorInfo) => {
console.error(
'Caught error',
error,
error.cause,
errorInfo.componentStack
);
}
}
);
```
The onRecoverableError option is a function called with two arguments:
1. The error React throws. Some errors may include the original cause as error.cause.
2. An errorInfo object that contains the componentStack of the error.
You can use the `onRecoverableError` root option to display error dialogs for hydration mismatches:
index.jsApp.js
index.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
import {reportRecoverableError} from "./reportError";
import "./styles.css";
const container = document.getElementById("root");
const root = hydrateRoot(container, <App />, {
onRecoverableError: (error, errorInfo) => {
reportRecoverableError({
error,
cause: error.cause,
componentStack: errorInfo.componentStack
});
}
});
```
## Troubleshooting[Link for Troubleshooting]()
### I’m getting an error: “You passed a second argument to root.render”[Link for I’m getting an error: “You passed a second argument to root.render”]()
A common mistake is to pass the options for `hydrateRoot` to `root.render(...)`:
Console
Warning: You passed a second argument to root.render(…) but it only accepts one argument.
To fix, pass the root options to `hydrateRoot(...)`, not `root.render(...)`:
```
// 🚩 Wrong: root.render only takes one argument.
root.render(App, {onUncaughtError});
// ✅ Correct: pass options to createRoot.
const root = hydrateRoot(container, <App />, {onUncaughtError});
```
[PreviouscreateRoot](https://react.dev/reference/react-dom/client/createRoot)
[NextServer APIs](https://react.dev/reference/react-dom/server) |
https://react.dev/blog/2024/04/25/react-19-upgrade-guide | [Blog](https://react.dev/blog)
# React 19 Upgrade Guide[Link for this heading]()
April 25, 2024 by [Ricky Hanlon](https://twitter.com/rickhanlonii)
* * *
The improvements added to React 19 require some breaking changes, but we’ve worked to make the upgrade as smooth as possible, and we don’t expect the changes to impact most apps.
### Note
#### React 18.3 has also been published[Link for React 18.3 has also been published]()
To help make the upgrade to React 19 easier, we’ve published a `[email protected]` release that is identical to 18.2 but adds warnings for deprecated APIs and other changes that are needed for React 19.
We recommend upgrading to React 18.3 first to help identify any issues before upgrading to React 19.
For a list of changes in 18.3 see the [Release Notes](https://github.com/facebook/react/blob/main/CHANGELOG.md).
In this post, we will guide you through the steps for upgrading to React 19:
- [Installing]()
- [Codemods]()
- [Breaking changes]()
- [New deprecations]()
- [Notable changes]()
- [TypeScript changes]()
- [Changelog]()
If you’d like to help us test React 19, follow the steps in this upgrade guide and [report any issues](https://github.com/facebook/react/issues/new?assignees=&labels=React%2019&projects=&template=19.md&title=%5BReact%2019%5D) you encounter. For a list of new features added to React 19, see the [React 19 release post](https://react.dev/blog/2024/12/05/react-19).
* * *
## Installing[Link for Installing]()
### Note
#### New JSX Transform is now required[Link for New JSX Transform is now required]()
We introduced a [new JSX transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) in 2020 to improve bundle size and use JSX without importing React. In React 19, we’re adding additional improvements like using ref as a prop and JSX speed improvements that require the new transform.
If the new transform is not enabled, you will see this warning:
Console
Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: [https://react.dev/link/new-jsx-transform](https://react.dev/link/new-jsx-transform)
We expect most apps will not be affected since the transform is enabled in most environments already. For manual instructions on how to upgrade, please see the [announcement post](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html).
To install the latest version of React and React DOM:
```
npm install --save-exact react@^19.0.0 react-dom@^19.0.0
```
Or, if you’re using Yarn:
```
yarn add --exact react@^19.0.0 react-dom@^19.0.0
```
If you’re using TypeScript, you also need to update the types.
```
npm install --save-exact @types/react@^19.0.0 @types/react-dom@^19.0.0
```
Or, if you’re using Yarn:
```
yarn add --exact @types/react@^19.0.0 @types/react-dom@^19.0.0
```
We’re also including a codemod for the most common replacements. See [TypeScript changes]() below.
## Codemods[Link for Codemods]()
To help with the upgrade, we’ve worked with the team at [codemod.com](https://codemod.com) to publish codemods that will automatically update your code to many of the new APIs and patterns in React 19.
All codemods are available in the [`react-codemod` repo](https://github.com/reactjs/react-codemod) and the Codemod team have joined in helping maintain the codemods. To run these codemods, we recommend using the `codemod` command instead of the `react-codemod` because it runs faster, handles more complex code migrations, and provides better support for TypeScript.
### Note
#### Run all React 19 codemods[Link for Run all React 19 codemods]()
Run all codemods listed in this guide with the React 19 `codemod` recipe:
```
npx codemod@latest react/19/migration-recipe
```
This will run the following codemods from `react-codemod`:
- [`replace-reactdom-render`](https://github.com/reactjs/react-codemod?tab=readme-ov-file)
- [`replace-string-ref`](https://github.com/reactjs/react-codemod?tab=readme-ov-file)
- [`replace-act-import`](https://github.com/reactjs/react-codemod?tab=readme-ov-file)
- [`replace-use-form-state`](https://github.com/reactjs/react-codemod?tab=readme-ov-file)
- [`prop-types-typescript`](https://codemod.com/registry/react-prop-types-typescript)
This does not include the TypeScript changes. See [TypeScript changes]() below.
Changes that include a codemod include the command below.
For a list of all available codemods, see the [`react-codemod` repo](https://github.com/reactjs/react-codemod).
## Breaking changes[Link for Breaking changes]()
### Errors in render are not re-thrown[Link for Errors in render are not re-thrown]()
In previous versions of React, errors thrown during render were caught and rethrown. In DEV, we would also log to `console.error`, resulting in duplicate error logs.
In React 19, we’ve [improved how errors are handled](https://react.dev/blog/2024/04/25/react-19) to reduce duplication by not re-throwing:
- **Uncaught Errors**: Errors that are not caught by an Error Boundary are reported to `window.reportError`.
- **Caught Errors**: Errors that are caught by an Error Boundary are reported to `console.error`.
This change should not impact most apps, but if your production error reporting relies on errors being re-thrown, you may need to update your error handling. To support this, we’ve added new methods to `createRoot` and `hydrateRoot` for custom error handling:
```
const root = createRoot(container, {
onUncaughtError: (error, errorInfo) => {
// ... log error report
},
onCaughtError: (error, errorInfo) => {
// ... log error report
}
});
```
For more info, see the docs for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot).
### Removed deprecated React APIs[Link for Removed deprecated React APIs]()
#### Removed: `propTypes` and `defaultProps` for functions[Link for this heading]()
`PropTypes` were deprecated in [April 2017 (v15.5.0)](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html).
In React 19, we’re removing the `propType` checks from the React package, and using them will be silently ignored. If you’re using `propTypes`, we recommend migrating to TypeScript or another type-checking solution.
We’re also removing `defaultProps` from function components in place of ES6 default parameters. Class components will continue to support `defaultProps` since there is no ES6 alternative.
```
// Before
import PropTypes from 'prop-types';
function Heading({text}) {
return <h1>{text}</h1>;
}
Heading.propTypes = {
text: PropTypes.string,
};
Heading.defaultProps = {
text: 'Hello, world!',
};
```
```
// After
interface Props {
text?: string;
}
function Heading({text = 'Hello, world!'}: Props) {
return <h1>{text}</h1>;
}
```
### Note
Codemod `propTypes` to TypeScript with:
```
npx codemod@latest react/prop-types-typescript
```
#### Removed: Legacy Context using `contextTypes` and `getChildContext`[Link for this heading]()
Legacy Context was deprecated in [October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html).
Legacy Context was only available in class components using the APIs `contextTypes` and `getChildContext`, and was replaced with `contextType` due to subtle bugs that were easy to miss. In React 19, we’re removing Legacy Context to make React slightly smaller and faster.
If you’re still using Legacy Context in class components, you’ll need to migrate to the new `contextType` API:
```
// Before
import PropTypes from 'prop-types';
class Parent extends React.Component {
static childContextTypes = {
foo: PropTypes.string.isRequired,
};
getChildContext() {
return { foo: 'bar' };
}
render() {
return <Child />;
}
}
class Child extends React.Component {
static contextTypes = {
foo: PropTypes.string.isRequired,
};
render() {
return <div>{this.context.foo}</div>;
}
}
```
```
// After
const FooContext = React.createContext();
class Parent extends React.Component {
render() {
return (
<FooContext value='bar'>
<Child />
</FooContext>
);
}
}
class Child extends React.Component {
static contextType = FooContext;
render() {
return <div>{this.context}</div>;
}
}
```
#### Removed: string refs[Link for Removed: string refs]()
String refs were deprecated in [March, 2018 (v16.3.0)](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html).
Class components supported string refs before being replaced by ref callbacks due to [multiple downsides](https://github.com/facebook/react/issues/1373). In React 19, we’re removing string refs to make React simpler and easier to understand.
If you’re still using string refs in class components, you’ll need to migrate to ref callbacks:
```
// Before
class MyComponent extends React.Component {
componentDidMount() {
this.refs.input.focus();
}
render() {
return <input ref='input' />;
}
}
```
```
// After
class MyComponent extends React.Component {
componentDidMount() {
this.input.focus();
}
render() {
return <input ref={input => this.input = input} />;
}
}
```
### Note
Codemod string refs with `ref` callbacks:
```
npx codemod@latest react/19/replace-string-ref
```
#### Removed: Module pattern factories[Link for Removed: Module pattern factories]()
Module pattern factories were deprecated in [August 2019 (v16.9.0)](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html).
This pattern was rarely used and supporting it causes React to be slightly larger and slower than necessary. In React 19, we’re removing support for module pattern factories, and you’ll need to migrate to regular functions:
```
// Before
function FactoryComponent() {
return { render() { return <div />; } }
}
```
```
// After
function FactoryComponent() {
return <div />;
}
```
#### Removed: `React.createFactory`[Link for this heading]()
`createFactory` was deprecated in [February 2020 (v16.13.0)](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html).
Using `createFactory` was common before broad support for JSX, but it’s rarely used today and can be replaced with JSX. In React 19, we’re removing `createFactory` and you’ll need to migrate to JSX:
```
// Before
import { createFactory } from 'react';
const button = createFactory('button');
```
```
// After
const button = <button />;
```
#### Removed: `react-test-renderer/shallow`[Link for this heading]()
In React 18, we updated `react-test-renderer/shallow` to re-export [react-shallow-renderer](https://github.com/enzymejs/react-shallow-renderer). In React 19, we’re removing `react-test-render/shallow` to prefer installing the package directly:
```
npm install react-shallow-renderer --save-dev
```
```
- import ShallowRenderer from 'react-test-renderer/shallow';
+ import ShallowRenderer from 'react-shallow-renderer';
```
### Note
##### Please reconsider shallow rendering[Link for Please reconsider shallow rendering]()
Shallow rendering depends on React internals and can block you from future upgrades. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro).
### Removed deprecated React DOM APIs[Link for Removed deprecated React DOM APIs]()
#### Removed: `react-dom/test-utils`[Link for this heading]()
We’ve moved `act` from `react-dom/test-utils` to the `react` package:
Console
`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. Import `act` from `react` instead of `react-dom/test-utils`. See [https://react.dev/warnings/react-dom-test-utils](https://react.dev/warnings/react-dom-test-utils) for more info.
To fix this warning, you can import `act` from `react`:
```
- import {act} from 'react-dom/test-utils'
+ import {act} from 'react';
```
All other `test-utils` functions have been removed. These utilities were uncommon, and made it too easy to depend on low level implementation details of your components and React. In React 19, these functions will error when called and their exports will be removed in a future version.
See the [warning page](https://react.dev/warnings/react-dom-test-utils) for alternatives.
### Note
Codemod `ReactDOMTestUtils.act` to `React.act`:
```
npx codemod@latest react/19/replace-act-import
```
#### Removed: `ReactDOM.render`[Link for this heading]()
`ReactDOM.render` was deprecated in [March 2022 (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). In React 19, we’re removing `ReactDOM.render` and you’ll need to migrate to using [`ReactDOM.createRoot`](https://react.dev/reference/react-dom/client/createRoot):
```
// Before
import {render} from 'react-dom';
render(<App />, document.getElementById('root'));
// After
import {createRoot} from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
```
### Note
Codemod `ReactDOM.render` to `ReactDOMClient.createRoot`:
```
npx codemod@latest react/19/replace-reactdom-render
```
#### Removed: `ReactDOM.hydrate`[Link for this heading]()
`ReactDOM.hydrate` was deprecated in [March 2022 (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). In React 19, we’re removing `ReactDOM.hydrate` you’ll need to migrate to using [`ReactDOM.hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot),
```
// Before
import {hydrate} from 'react-dom';
hydrate(<App />, document.getElementById('root'));
// After
import {hydrateRoot} from 'react-dom/client';
hydrateRoot(document.getElementById('root'), <App />);
```
### Note
Codemod `ReactDOM.hydrate` to `ReactDOMClient.hydrateRoot`:
```
npx codemod@latest react/19/replace-reactdom-render
```
#### Removed: `unmountComponentAtNode`[Link for this heading]()
`ReactDOM.unmountComponentAtNode` was deprecated in [March 2022 (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). In React 19, you’ll need to migrate to using `root.unmount()`.
```
// Before
unmountComponentAtNode(document.getElementById('root'));
// After
root.unmount();
```
For more see `root.unmount()` for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot).
### Note
Codemod `unmountComponentAtNode` to `root.unmount`:
```
npx codemod@latest react/19/replace-reactdom-render
```
#### Removed: `ReactDOM.findDOMNode`[Link for this heading]()
`ReactDOM.findDOMNode` was [deprecated in October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html).
We’re removing `findDOMNode` because it was a legacy escape hatch that was slow to execute, fragile to refactoring, only returned the first child, and broke abstraction levels (see more [here](https://legacy.reactjs.org/docs/strict-mode.html)). You can replace `ReactDOM.findDOMNode` with [DOM refs](https://react.dev/learn/manipulating-the-dom-with-refs):
```
// Before
import {findDOMNode} from 'react-dom';
function AutoselectingInput() {
useEffect(() => {
const input = findDOMNode(this);
input.select()
}, []);
return <input defaultValue="Hello" />;
}
```
```
// After
function AutoselectingInput() {
const ref = useRef(null);
useEffect(() => {
ref.current.select();
}, []);
return <input ref={ref} defaultValue="Hello" />
}
```
## New deprecations[Link for New deprecations]()
### Deprecated: `element.ref`[Link for this heading]()
React 19 supports [`ref` as a prop](https://react.dev/blog/2024/04/25/react-19), so we’re deprecating the `element.ref` in place of `element.props.ref`.
Accessing `element.ref` will warn:
Console
Accessing element.ref is no longer supported. ref is now a regular prop. It will be removed from the JSX Element type in a future release.
### Deprecated: `react-test-renderer`[Link for this heading]()
We are deprecating `react-test-renderer` because it implements its own renderer environment that doesn’t match the environment users use, promotes testing implementation details, and relies on introspection of React’s internals.
The test renderer was created before there were more viable testing strategies available like [React Testing Library](https://testing-library.com), and we now recommend using a modern testing library instead.
In React 19, `react-test-renderer` logs a deprecation warning, and has switched to concurrent rendering. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro) for a modern and well supported testing experience.
## Notable changes[Link for Notable changes]()
### StrictMode changes[Link for StrictMode changes]()
React 19 includes several fixes and improvements to Strict Mode.
When double rendering in Strict Mode in development, `useMemo` and `useCallback` will reuse the memoized results from the first render during the second render. Components that are already Strict Mode compatible should not notice a difference in behavior.
As with all Strict Mode behaviors, these features are designed to proactively surface bugs in your components during development so you can fix them before they are shipped to production. For example, during development, Strict Mode will double-invoke ref callback functions on initial mount, to simulate what happens when a mounted component is replaced by a Suspense fallback.
### Improvements to Suspense[Link for Improvements to Suspense]()
In React 19, when a component suspends, React will immediately commit the fallback of the nearest Suspense boundary without waiting for the entire sibling tree to render. After the fallback commits, React schedules another render for the suspended siblings to “pre-warm” lazy requests in the rest of the tree:
![Diagram showing a tree of three components, one parent labeled Accordion and two children labeled Panel. Both Panel components contain isActive with value false.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fprerender.dark.png&w=3840&q=75)
![Diagram showing a tree of three components, one parent labeled Accordion and two children labeled Panel. Both Panel components contain isActive with value false.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fprerender.png&w=3840&q=75)
Previously, when a component suspended, the suspended siblings were rendered and then the fallback was committed.
![The same diagram as the previous, with the isActive of the first child Panel component highlighted indicating a click with the isActive value set to true. The second Panel component still contains value false.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fprewarm.dark.png&w=3840&q=75)
![The same diagram as the previous, with the isActive of the first child Panel component highlighted indicating a click with the isActive value set to true. The second Panel component still contains value false.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fprewarm.png&w=3840&q=75)
In React 19, when a component suspends, the fallback is committed and then the suspended siblings are rendered.
This change means Suspense fallbacks display faster, while still warming lazy requests in the suspended tree.
### UMD builds removed[Link for UMD builds removed]()
UMD was widely used in the past as a convenient way to load React without a build step. Now, there are modern alternatives for loading modules as scripts in HTML documents. Starting with React 19, React will no longer produce UMD builds to reduce the complexity of its testing and release process.
To load React 19 with a script tag, we recommend using an ESM-based CDN such as [esm.sh](https://esm.sh/).
```
<script type="module">
import React from "https://esm.sh/react@19/?dev"
import ReactDOMClient from "https://esm.sh/react-dom@19/client?dev"
...
</script>
```
### Libraries depending on React internals may block upgrades[Link for Libraries depending on React internals may block upgrades]()
This release includes changes to React internals that may impact libraries that ignore our pleas to not use internals like `SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED`. These changes are necessary to land improvements in React 19, and will not break libraries that follow our guidelines.
Based on our [Versioning Policy](https://react.dev/community/versioning-policy), these updates are not listed as breaking changes, and we are not including docs for how to upgrade them. The recommendation is to remove any code that depends on internals.
To reflect the impact of using internals, we have renamed the `SECRET_INTERNALS` suffix to:
`_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE`
In the future we will more aggressively block accessing internals from React to discourage usage and ensure users are not blocked from upgrading.
## TypeScript changes[Link for TypeScript changes]()
### Removed deprecated TypeScript types[Link for Removed deprecated TypeScript types]()
We’ve cleaned up the TypeScript types based on the removed APIs in React 19. Some of the removed have types been moved to more relevant packages, and others are no longer needed to describe React’s behavior.
### Note
We’ve published [`types-react-codemod`](https://github.com/eps1lon/types-react-codemod/) to migrate most type related breaking changes:
```
npx types-react-codemod@latest preset-19 ./path-to-app
```
If you have a lot of unsound access to `element.props`, you can run this additional codemod:
```
npx types-react-codemod@latest react-element-default-any-props ./path-to-your-react-ts-files
```
Check out [`types-react-codemod`](https://github.com/eps1lon/types-react-codemod/) for a list of supported replacements. If you feel a codemod is missing, it can be tracked in the [list of missing React 19 codemods](https://github.com/eps1lon/types-react-codemod/issues?q=is%3Aissue%20is%3Aopen%20sort%3Aupdated-desc%20label%3A%22React%2019%22%20label%3Aenhancement).
### `ref` cleanups required[Link for this heading]()
*This change is included in the `react-19` codemod preset as [`no-implicit-ref-callback-return`](https://github.com/eps1lon/types-react-codemod/).*
Due to the introduction of ref cleanup functions, returning anything else from a ref callback will now be rejected by TypeScript. The fix is usually to stop using implicit returns:
```
- <div ref={current => (instance = current)} />
+ <div ref={current => {instance = current}} />
```
The original code returned the instance of the `HTMLDivElement` and TypeScript wouldn’t know if this was supposed to be a cleanup function or not.
### `useRef` requires an argument[Link for this heading]()
*This change is included in the `react-19` codemod preset as [`refobject-defaults`](https://github.com/eps1lon/types-react-codemod/).*
A long-time complaint of how TypeScript and React work has been `useRef`. We’ve changed the types so that `useRef` now requires an argument. This significantly simplifies its type signature. It’ll now behave more like `createContext`.
```
// @ts-expect-error: Expected 1 argument but saw none
useRef();
// Passes
useRef(undefined);
// @ts-expect-error: Expected 1 argument but saw none
createContext();
// Passes
createContext(undefined);
```
This now also means that all refs are mutable. You’ll no longer hit the issue where you can’t mutate a ref because you initialised it with `null`:
```
const ref = useRef<number>(null);
// Cannot assign to 'current' because it is a read-only property
ref.current = 1;
```
`MutableRef` is now deprecated in favor of a single `RefObject` type which `useRef` will always return:
```
interface RefObject<T> {
current: T
}
declare function useRef<T>: RefObject<T>
```
`useRef` still has a convenience overload for `useRef<T>(null)` that automatically returns `RefObject<T | null>`. To ease migration due to the required argument for `useRef`, a convenience overload for `useRef(undefined)` was added that automatically returns `RefObject<T | undefined>`.
Check out [\[RFC\] Make all refs mutable](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/64772) for prior discussions about this change.
### Changes to the `ReactElement` TypeScript type[Link for this heading]()
*This change is included in the [`react-element-default-any-props`](https://github.com/eps1lon/types-react-codemod) codemod.*
The `props` of React elements now default to `unknown` instead of `any` if the element is typed as `ReactElement`. This does not affect you if you pass a type argument to `ReactElement`:
```
type Example2 = ReactElement<{ id: string }>["props"];
// ^? { id: string }
```
But if you relied on the default, you now have to handle `unknown`:
```
type Example = ReactElement["props"];
// ^? Before, was 'any', now 'unknown'
```
You should only need it if you have a lot of legacy code relying on unsound access of element props. Element introspection only exists as an escape hatch, and you should make it explicit that your props access is unsound via an explicit `any`.
### The JSX namespace in TypeScript[Link for The JSX namespace in TypeScript]()
This change is included in the `react-19` codemod preset as [`scoped-jsx`](https://github.com/eps1lon/types-react-codemod)
A long-time request is to remove the global `JSX` namespace from our types in favor of `React.JSX`. This helps prevent pollution of global types which prevents conflicts between different UI libraries that leverage JSX.
You’ll now need to wrap module augmentation of the JSX namespace in \`declare module ”…”:
```
// global.d.ts
+ declare module "react" {
namespace JSX {
interface IntrinsicElements {
"my-element": {
myElementProps: string;
};
}
}
+ }
```
The exact module specifier depends on the JSX runtime you specified in the `compilerOptions` of your `tsconfig.json`:
- For `"jsx": "react-jsx"` it would be `react/jsx-runtime`.
- For `"jsx": "react-jsxdev"` it would be `react/jsx-dev-runtime`.
- For `"jsx": "react"` and `"jsx": "preserve"` it would be `react`.
### Better `useReducer` typings[Link for this heading]()
`useReducer` now has improved type inference thanks to [@mfp22](https://github.com/mfp22).
However, this required a breaking change where `useReducer` doesn’t accept the full reducer type as a type parameter but instead either needs none (and rely on contextual typing) or needs both the state and action type.
The new best practice is *not* to pass type arguments to `useReducer`.
```
- useReducer<React.Reducer<State, Action>>(reducer)
+ useReducer(reducer)
```
This may not work in edge cases where you can explicitly type the state and action, by passing in the `Action` in a tuple:
```
- useReducer<React.Reducer<State, Action>>(reducer)
+ useReducer<State, [Action]>(reducer)
```
If you define the reducer inline, we encourage to annotate the function parameters instead:
```
- useReducer<React.Reducer<State, Action>>((state, action) => state)
+ useReducer((state: State, action: Action) => state)
```
This is also what you’d also have to do if you move the reducer outside of the `useReducer` call:
```
const reducer = (state: State, action: Action) => state;
```
## Changelog[Link for Changelog]()
### Other breaking changes[Link for Other breaking changes]()
- **react-dom**: Error for javascript URLs in `src` and `href` [#26507](https://github.com/facebook/react/pull/26507)
- **react-dom**: Remove `errorInfo.digest` from `onRecoverableError` [#28222](https://github.com/facebook/react/pull/28222)
- **react-dom**: Remove `unstable_flushControlled` [#26397](https://github.com/facebook/react/pull/26397)
- **react-dom**: Remove `unstable_createEventHandle` [#28271](https://github.com/facebook/react/pull/28271)
- **react-dom**: Remove `unstable_renderSubtreeIntoContainer` [#28271](https://github.com/facebook/react/pull/28271)
- **react-dom**: Remove `unstable_runWithPriority` [#28271](https://github.com/facebook/react/pull/28271)
- **react-is**: Remove deprecated methods from `react-is` [28224](https://github.com/facebook/react/pull/28224)
### Other notable changes[Link for Other notable changes]()
- **react**: Batch sync, default and continuous lanes [#25700](https://github.com/facebook/react/pull/25700)
- **react**: Don’t prerender siblings of suspended component [#26380](https://github.com/facebook/react/pull/26380)
- **react**: Detect infinite update loops caused by render phase updates [#26625](https://github.com/facebook/react/pull/26625)
- **react-dom**: Transitions in popstate are now synchronous [#26025](https://github.com/facebook/react/pull/26025)
- **react-dom**: Remove layout effect warning during SSR [#26395](https://github.com/facebook/react/pull/26395)
- **react-dom**: Warn and don’t set empty string for src/href (except anchor tags) [#28124](https://github.com/facebook/react/pull/28124)
For a full list of changes, please see the [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md).
* * *
Thanks to [Andrew Clark](https://twitter.com/acdlite), [Eli White](https://twitter.com/Eli_White), [Jack Pope](https://github.com/jackpope), [Jan Kassens](https://github.com/kassens), [Josh Story](https://twitter.com/joshcstory), [Matt Carroll](https://twitter.com/mattcarrollcode), [Noah Lemen](https://twitter.com/noahlemen), [Sophie Alpert](https://twitter.com/sophiebits), and [Sebastian Silbermann](https://twitter.com/sebsilbermann) for reviewing and editing this post.
[PreviousReact 19 RC](https://react.dev/blog/2024/04/25/react-19)
[NextReact Labs: What We've Been Working On – February 2024](https://react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024) |
https://react.dev/reference/react-dom/server/renderToPipeableStream | [API Reference](https://react.dev/reference/react)
[Server APIs](https://react.dev/reference/react-dom/server)
# renderToPipeableStream[Link for this heading]()
`renderToPipeableStream` renders a React tree to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html)
```
const { pipe, abort } = renderToPipeableStream(reactNode, options?)
```
- [Reference]()
- [`renderToPipeableStream(reactNode, options?)`]()
- [Usage]()
- [Rendering a React tree as HTML to a Node.js Stream]()
- [Streaming more content as it loads]()
- [Specifying what goes into the shell]()
- [Logging crashes on the server]()
- [Recovering from errors inside the shell]()
- [Recovering from errors outside the shell]()
- [Setting the status code]()
- [Handling different errors in different ways]()
- [Waiting for all content to load for crawlers and static generation]()
- [Aborting server rendering]()
### Note
This API is specific to Node.js. Environments with [Web Streams,](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) like Deno and modern edge runtimes, should use [`renderToReadableStream`](https://react.dev/reference/react-dom/server/renderToReadableStream) instead.
* * *
## Reference[Link for Reference]()
### `renderToPipeableStream(reactNode, options?)`[Link for this heading]()
Call `renderToPipeableStream` to render your React tree as HTML into a [Node.js Stream.](https://nodejs.org/api/stream.html)
```
import { renderToPipeableStream } from 'react-dom/server';
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
```
On the client, call [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `reactNode`: A React node you want to render to HTML. For example, a JSX element like `<App />`. It is expected to represent the entire document, so the `App` component should render the `<html>` tag.
- **optional** `options`: An object with streaming options.
- **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline `<script>` tag.
- **optional** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](https://react.dev/reference/react-dom/client/hydrateRoot) Omit it if you don’t want to run React on the client at all.
- **optional** `bootstrapModules`: Like `bootstrapScripts`, but emits [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) instead.
- **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](https://react.dev/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](https://react.dev/reference/react-dom/client/hydrateRoot)
- **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
- **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
- **optional** `onAllReady`: A callback that fires when all rendering is complete, including both the [shell]() and all additional [content.]() You can use this instead of `onShellReady` [for crawlers and static generation.]() If you start streaming here, you won’t get any progressive loading. The stream will contain the final HTML.
- **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable]() or [not.]() By default, this only calls `console.error`. If you override it to [log crash reports,]() make sure that you still call `console.error`. You can also use it to [adjust the status code]() before the shell is emitted.
- **optional** `onShellReady`: A callback that fires right after the [initial shell]() has been rendered. You can [set the status code]() and call `pipe` here to start streaming. React will [stream the additional content]() after the shell along with the inline `<script>` tags that replace the HTML loading fallbacks with the content.
- **optional** `onShellError`: A callback that fires if there was an error rendering the initial shell. It receives the error as an argument. No bytes were emitted from the stream yet, and neither `onShellReady` nor `onAllReady` will get called, so you can [output a fallback HTML shell.]()
- **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js)
#### Returns[Link for Returns]()
`renderToPipeableStream` returns an object with two methods:
- `pipe` outputs the HTML into the provided [Writable Node.js Stream.](https://nodejs.org/api/stream.html) Call `pipe` in `onShellReady` if you want to enable streaming, or in `onAllReady` for crawlers and static generation.
- `abort` lets you [abort server rendering]() and render the rest on the client.
* * *
## Usage[Link for Usage]()
### Rendering a React tree as HTML to a Node.js Stream[Link for Rendering a React tree as HTML to a Node.js Stream]()
Call `renderToPipeableStream` to render your React tree as HTML into a [Node.js Stream:](https://nodejs.org/api/stream.html)
```
import { renderToPipeableStream } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
});
```
Along with the root component, you need to provide a list of bootstrap `<script>` paths. Your root component should return **the entire document including the root `<html>` tag.**
For example, it might look like this:
```
export default function App() {
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/styles.css"></link>
<title>My app</title>
</head>
<body>
<Router />
</body>
</html>
);
}
```
React will inject the [doctype](https://developer.mozilla.org/en-US/docs/Glossary/Doctype) and your bootstrap `<script>` tags into the resulting HTML stream:
```
<!DOCTYPE html>
<html>
<!-- ... HTML from your components ... -->
</html>
<script src="/main.js" async=""></script>
```
On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](https://react.dev/reference/react-dom/client/hydrateRoot)
```
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);
```
This will attach event listeners to the server-generated HTML and make it interactive.
##### Deep Dive
#### Reading CSS and JS asset paths from the build output[Link for Reading CSS and JS asset paths from the build output]()
Show Details
The final asset URLs (like JavaScript and CSS files) are often hashed after the build. For example, instead of `styles.css` you might end up with `styles.123456.css`. Hashing static asset filenames guarantees that every distinct build of the same asset will have a different filename. This is useful because it lets you safely enable long-term caching for static assets: a file with a certain name would never change content.
However, if you don’t know the asset URLs until after the build, there’s no way for you to put them in the source code. For example, hardcoding `"/styles.css"` into JSX like earlier wouldn’t work. To keep them out of your source code, your root component can read the real filenames from a map passed as a prop:
```
export default function App({ assetMap }) {
return (
<html>
<head>
...
<link rel="stylesheet" href={assetMap['styles.css']}></link>
...
</head>
...
</html>
);
}
```
On the server, render `<App assetMap={assetMap} />` and pass your `assetMap` with the asset URLs:
```
// You'd need to get this JSON from your build tooling, e.g. read it from the build output.
const assetMap = {
'styles.css': '/styles.123456.css',
'main.js': '/main.123456.js'
};
app.use('/', (request, response) => {
const { pipe } = renderToPipeableStream(<App assetMap={assetMap} />, {
bootstrapScripts: [assetMap['main.js']],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
});
```
Since your server is now rendering `<App assetMap={assetMap} />`, you need to render it with `assetMap` on the client too to avoid hydration errors. You can serialize and pass `assetMap` to the client like this:
```
// You'd need to get this JSON from your build tooling.
const assetMap = {
'styles.css': '/styles.123456.css',
'main.js': '/main.123456.js'
};
app.use('/', (request, response) => {
const { pipe } = renderToPipeableStream(<App assetMap={assetMap} />, {
// Careful: It's safe to stringify() this because this data isn't user-generated.
bootstrapScriptContent: `window.assetMap = ${JSON.stringify(assetMap)};`,
bootstrapScripts: [assetMap['main.js']],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
});
```
In the example above, the `bootstrapScriptContent` option adds an extra inline `<script>` tag that sets the global `window.assetMap` variable on the client. This lets the client code read the same `assetMap`:
```
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App assetMap={window.assetMap} />);
```
Both client and server render `App` with the same `assetMap` prop, so there are no hydration errors.
* * *
### Streaming more content as it loads[Link for Streaming more content as it loads]()
Streaming allows the user to start seeing the content even before all the data has loaded on the server. For example, consider a profile page that shows a cover, a sidebar with friends and photos, and a list of posts:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Posts />
</ProfileLayout>
);
}
```
Imagine that loading data for `<Posts />` takes some time. Ideally, you’d want to show the rest of the profile page content to the user without waiting for the posts. To do this, [wrap `Posts` in a `<Suspense>` boundary:](https://react.dev/reference/react/Suspense)
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
```
This tells React to start streaming the HTML before `Posts` loads its data. React will send the HTML for the loading fallback (`PostsGlimmer`) first, and then, when `Posts` finishes loading its data, React will send the remaining HTML along with an inline `<script>` tag that replaces the loading fallback with that HTML. From the user’s perspective, the page will first appear with the `PostsGlimmer`, later replaced by the `Posts`.
You can further [nest `<Suspense>` boundaries](https://react.dev/reference/react/Suspense) to create a more granular loading sequence:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<BigSpinner />}>
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</Suspense>
</ProfileLayout>
);
}
```
In this example, React can start streaming the page even earlier. Only `ProfileLayout` and `ProfileCover` must finish rendering first because they are not wrapped in any `<Suspense>` boundary. However, if `Sidebar`, `Friends`, or `Photos` need to load some data, React will send the HTML for the `BigSpinner` fallback instead. Then, as more data becomes available, more content will continue to be revealed until all of it becomes visible.
Streaming does not need to wait for React itself to load in the browser, or for your app to become interactive. The HTML content from the server will get progressively revealed before any of the `<script>` tags load.
[Read more about how streaming HTML works.](https://github.com/reactwg/react-18/discussions/37)
### Note
**Only Suspense-enabled data sources will activate the Suspense component.** They include:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/getting-started/react-essentials)
- Lazy-loading component code with [`lazy`](https://react.dev/reference/react/lazy)
- Reading the value of a Promise with [`use`](https://react.dev/reference/react/use)
Suspense **does not** detect when data is fetched inside an Effect or event handler.
The exact way you would load data in the `Posts` component above depends on your framework. If you use a Suspense-enabled framework, you’ll find the details in its data fetching documentation.
Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React.
* * *
### Specifying what goes into the shell[Link for Specifying what goes into the shell]()
The part of your app outside of any `<Suspense>` boundaries is called *the shell:*
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<BigSpinner />}>
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</Suspense>
</ProfileLayout>
);
}
```
It determines the earliest loading state that the user may see:
```
<ProfileLayout>
<ProfileCover />
<BigSpinner />
</ProfileLayout>
```
If you wrap the whole app into a `<Suspense>` boundary at the root, the shell will only contain that spinner. However, that’s not a pleasant user experience because seeing a big spinner on the screen can feel slower and more annoying than waiting a bit more and seeing the real layout. This is why usually you’ll want to place the `<Suspense>` boundaries so that the shell feels *minimal but complete*—like a skeleton of the entire page layout.
The `onShellReady` callback fires when the entire shell has been rendered. Usually, you’ll start streaming then:
```
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
```
By the time `onShellReady` fires, components in nested `<Suspense>` boundaries might still be loading data.
* * *
### Logging crashes on the server[Link for Logging crashes on the server]()
By default, all errors on the server are logged to console. You can override this behavior to log crash reports:
```
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
},
onError(error) {
console.error(error);
logServerCrashReport(error);
}
});
```
If you provide a custom `onError` implementation, don’t forget to also log errors to the console like above.
* * *
### Recovering from errors inside the shell[Link for Recovering from errors inside the shell]()
In this example, the shell contains `ProfileLayout`, `ProfileCover`, and `PostsGlimmer`:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
```
If an error occurs while rendering those components, React won’t have any meaningful HTML to send to the client. Override `onShellError` to send a fallback HTML that doesn’t rely on server rendering as the last resort:
```
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
},
onShellError(error) {
response.statusCode = 500;
response.setHeader('content-type', 'text/html');
response.send('<h1>Something went wrong</h1>');
},
onError(error) {
console.error(error);
logServerCrashReport(error);
}
});
```
If there is an error while generating the shell, both `onError` and `onShellError` will fire. Use `onError` for error reporting and use `onShellError` to send the fallback HTML document. Your fallback HTML does not have to be an error page. Instead, you may include an alternative shell that renders your app on the client only.
* * *
### Recovering from errors outside the shell[Link for Recovering from errors outside the shell]()
In this example, the `<Posts />` component is wrapped in `<Suspense>` so it is *not* a part of the shell:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
```
If an error happens in the `Posts` component or somewhere inside it, React will [try to recover from it:](https://react.dev/reference/react/Suspense)
1. It will emit the loading fallback for the closest `<Suspense>` boundary (`PostsGlimmer`) into the HTML.
2. It will “give up” on trying to render the `Posts` content on the server anymore.
3. When the JavaScript code loads on the client, React will *retry* rendering `Posts` on the client.
If retrying rendering `Posts` on the client *also* fails, React will throw the error on the client. As with all the errors thrown during rendering, the [closest parent error boundary](https://react.dev/reference/react/Component) determines how to present the error to the user. In practice, this means that the user will see a loading indicator until it is certain that the error is not recoverable.
If retrying rendering `Posts` on the client succeeds, the loading fallback from the server will be replaced with the client rendering output. The user will not know that there was a server error. However, the server `onError` callback and the client [`onRecoverableError`](https://react.dev/reference/react-dom/client/hydrateRoot) callbacks will fire so that you can get notified about the error.
* * *
### Setting the status code[Link for Setting the status code]()
Streaming introduces a tradeoff. You want to start streaming the page as early as possible so that the user can see the content sooner. However, once you start streaming, you can no longer set the response status code.
By [dividing your app]() into the shell (above all `<Suspense>` boundaries) and the rest of the content, you’ve already solved a part of this problem. If the shell errors, you’ll get the `onShellError` callback which lets you set the error status code. Otherwise, you know that the app may recover on the client, so you can send “OK”.
```
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.statusCode = 200;
response.setHeader('content-type', 'text/html');
pipe(response);
},
onShellError(error) {
response.statusCode = 500;
response.setHeader('content-type', 'text/html');
response.send('<h1>Something went wrong</h1>');
},
onError(error) {
console.error(error);
logServerCrashReport(error);
}
});
```
If a component *outside* the shell (i.e. inside a `<Suspense>` boundary) throws an error, React will not stop rendering. This means that the `onError` callback will fire, but you will still get `onShellReady` instead of `onShellError`. This is because React will try to recover from that error on the client, [as described above.]()
However, if you’d like, you can use the fact that something has errored to set the status code:
```
let didError = false;
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.statusCode = didError ? 500 : 200;
response.setHeader('content-type', 'text/html');
pipe(response);
},
onShellError(error) {
response.statusCode = 500;
response.setHeader('content-type', 'text/html');
response.send('<h1>Something went wrong</h1>');
},
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
```
This will only catch errors outside the shell that happened while generating the initial shell content, so it’s not exhaustive. If knowing whether an error occurred for some content is critical, you can move it up into the shell.
* * *
### Handling different errors in different ways[Link for Handling different errors in different ways]()
You can [create your own `Error` subclasses](https://javascript.info/custom-errors) and use the [`instanceof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) operator to check which error is thrown. For example, you can define a custom `NotFoundError` and throw it from your component. Then your `onError`, `onShellReady`, and `onShellError` callbacks can do something different depending on the error type:
```
let didError = false;
let caughtError = null;
function getStatusCode() {
if (didError) {
if (caughtError instanceof NotFoundError) {
return 404;
} else {
return 500;
}
} else {
return 200;
}
}
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.statusCode = getStatusCode();
response.setHeader('content-type', 'text/html');
pipe(response);
},
onShellError(error) {
response.statusCode = getStatusCode();
response.setHeader('content-type', 'text/html');
response.send('<h1>Something went wrong</h1>');
},
onError(error) {
didError = true;
caughtError = error;
console.error(error);
logServerCrashReport(error);
}
});
```
Keep in mind that once you emit the shell and start streaming, you can’t change the status code.
* * *
### Waiting for all content to load for crawlers and static generation[Link for Waiting for all content to load for crawlers and static generation]()
Streaming offers a better user experience because the user can see the content as it becomes available.
However, when a crawler visits your page, or if you’re generating the pages at the build time, you might want to let all of the content load first and then produce the final HTML output instead of revealing it progressively.
You can wait for all the content to load using the `onAllReady` callback:
```
let didError = false;
let isCrawler = // ... depends on your bot detection strategy ...
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
if (!isCrawler) {
response.statusCode = didError ? 500 : 200;
response.setHeader('content-type', 'text/html');
pipe(response);
}
},
onShellError(error) {
response.statusCode = 500;
response.setHeader('content-type', 'text/html');
response.send('<h1>Something went wrong</h1>');
},
onAllReady() {
if (isCrawler) {
response.statusCode = didError ? 500 : 200;
response.setHeader('content-type', 'text/html');
pipe(response);
}
},
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
```
A regular visitor will get a stream of progressively loaded content. A crawler will receive the final HTML output after all the data loads. However, this also means that the crawler will have to wait for *all* data, some of which might be slow to load or error. Depending on your app, you could choose to send the shell to the crawlers too.
* * *
### Aborting server rendering[Link for Aborting server rendering]()
You can force the server rendering to “give up” after a timeout:
```
const { pipe, abort } = renderToPipeableStream(<App />, {
// ...
});
setTimeout(() => {
abort();
}, 10000);
```
React will flush the remaining loading fallbacks as HTML, and will attempt to render the rest on the client.
[PreviousServer APIs](https://react.dev/reference/react-dom/server)
[NextrenderToReadableStream](https://react.dev/reference/react-dom/server/renderToReadableStream) |
https://react.dev/blog/2023/05/03/react-canaries | [Blog](https://react.dev/blog)
# React Canaries: Enabling Incremental Feature Rollout Outside Meta[Link for this heading]()
May 3, 2023 by [Dan Abramov](https://twitter.com/dan_abramov), [Sophie Alpert](https://twitter.com/sophiebits), [Rick Hanlon](https://twitter.com/rickhanlonii), [Sebastian Markbåge](https://twitter.com/sebmarkbage), and [Andrew Clark](https://twitter.com/acdlite)
* * *
We’d like to offer the React community an option to adopt individual new features as soon as their design is close to final, before they’re released in a stable version—similar to how Meta has long used bleeding-edge versions of React internally. We are introducing a new officially supported [Canary release channel](https://react.dev/community/versioning-policy). It lets curated setups like frameworks decouple adoption of individual React features from the React release schedule.
* * *
## tl;dr[Link for tl;dr]()
- We’re introducing an officially supported [Canary release channel](https://react.dev/community/versioning-policy) for React. Since it’s officially supported, if any regressions land, we’ll treat them with a similar urgency to bugs in stable releases.
- Canaries let you start using individual new React features before they land in the semver-stable releases.
- Unlike the [Experimental](https://react.dev/community/versioning-policy) channel, React Canaries only include features that we reasonably believe to be ready for adoption. We encourage frameworks to consider bundling pinned Canary React releases.
- We will announce breaking changes and new features on our blog as they land in Canary releases.
- **As always, React continues to follow semver for every Stable release.**
## How React features are usually developed[Link for How React features are usually developed]()
Typically, every React feature has gone through the same stages:
1. We develop an initial version and prefix it with `experimental_` or `unstable_`. The feature is only available in the `experimental` release channel. At this point, the feature is expected to change significantly.
2. We find a team at Meta willing to help us test this feature and provide feedback on it. This leads to a round of changes. As the feature becomes more stable, we work with more teams at Meta to try it out.
3. Eventually, we feel confident in the design. We remove the prefix from the API name, and make the feature available on the `main` branch by default, which most Meta products use. At this point, any team at Meta can use this feature.
4. As we build confidence in the direction, we also post an RFC for the new feature. At this point we know the design works for a broad set of cases, but we might make some last minute adjustments.
5. When we are close to cutting an open source release, we write documentation for the feature and finally release the feature in a stable React release.
This playbook works well for most features we’ve released so far. However, there can be a significant gap between when the feature is generally ready to use (step 3) and when it is released in open source (step 5).
**We’d like to offer the React community an option to follow the same approach as Meta, and adopt individual new features earlier (as they become available) without having to wait for the next release cycle of React.**
As always, all React features will eventually make it into a Stable release.
## Can we just do more minor releases?[Link for Can we just do more minor releases?]()
Generally, we *do* use minor releases for introducing new features.
However, this isn’t always possible. Sometimes, new features are interconnected with *other* new features which have not yet been fully completed and that we’re still actively iterating on. We can’t release them separately because their implementations are related. We can’t version them separately because they affect the same packages (for example, `react` and `react-dom`). And we need to keep the ability to iterate on the pieces that aren’t ready without a flurry of major version releases, which semver would require us to do.
At Meta, we’ve solved this problem by building React from the `main` branch, and manually updating it to a specific pinned commit every week. This is also the approach that React Native releases have been following for the last several years. Every *stable* release of React Native is pinned to a specific commit from the `main` branch of the React repository. This lets React Native include important bugfixes and incrementally adopt new React features at the framework level without getting coupled to the global React release schedule.
We would like to make this workflow available to other frameworks and curated setups. For example, it lets a framework *on top of* React include a React-related breaking change *before* this breaking change gets included into a stable React release. This is particularly useful because some breaking changes only affect framework integrations. This lets a framework release such a change in its own minor version without breaking semver.
Rolling releases with the Canaries channel will allow us to have a tighter feedback loop and ensure that new features get comprehensive testing in the community. This workflow is closer to how TC39, the JavaScript standards committee, [handles changes in numbered stages](https://tc39.es/process-document/). New React features may be available in frameworks built on React before they are in a React stable release, just as new JavaScript features ship in browsers before they are officially ratified as part of the specification.
## Why not use experimental releases instead?[Link for Why not use experimental releases instead?]()
Although you *can* technically use [Experimental releases](https://react.dev/community/versioning-policy), we recommend against using them in production because experimental APIs can undergo significant breaking changes on their way to stabilization (or can even be removed entirely). While Canaries can also contain mistakes (as with any release), going forward we plan to announce any significant breaking changes in Canaries on our blog. Canaries are the closest to the code Meta runs internally, so you can generally expect them to be relatively stable. However, you *do* need to keep the version pinned and manually scan the GitHub commit log when updating between the pinned commits.
**We expect that most people using React outside a curated setup (like a framework) will want to continue using the Stable releases.** However, if you’re building a framework, you might want to consider bundling a Canary version of React pinned to a particular commit, and update it at your own pace. The benefit of that is that it lets you ship individual completed React features and bugfixes earlier for your users and at your own release schedule, similar to how React Native has been doing it for the last few years. The downside is that you would take on additional responsibility to review which React commits are being pulled in and communicate to your users which React changes are included with your releases.
If you’re a framework author and want to try this approach, please get in touch with us.
## Announcing breaking changes and new features early[Link for Announcing breaking changes and new features early]()
Canary releases represent our best guess of what will go into the next stable React release at any given time.
Traditionally, we’ve only announced breaking changes at the *end* of the release cycle (when doing a major release). Now that Canary releases are an officially supported way to consume React, we plan to shift towards announcing breaking changes and significant new features *as they land* in Canaries. For example, if we merge a breaking change that will go out in a Canary, we will write a post about it on the React blog, including codemods and migration instructions if necessary. Then, if you’re a framework author cutting a major release that updates the pinned React canary to include that change, you can link to our blog post from your release notes. Finally, when a stable major version of React is ready, we will link to those already published blog posts, which we hope will help our team make progress faster.
We plan to document APIs as they land in Canaries—even if these APIs are not yet available outside of them. APIs that are only available in Canaries will be marked with a special note on the corresponding pages. This will include APIs like [`use`](https://github.com/reactjs/rfcs/pull/229), and some others (like `cache` and `createServerContext`) which we’ll send RFCs for.
## Canaries must be pinned[Link for Canaries must be pinned]()
If you decide to adopt the Canary workflow for your app or framework, make sure you always pin the *exact* version of the Canary you’re using. Since Canaries are pre-releases, they may still include breaking changes.
## Example: React Server Components[Link for Example: React Server Components]()
As we [announced in March](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023), the React Server Components conventions have been finalized, and we do not expect significant breaking changes related to their user-facing API contract. However, we can’t release support for React Server Components in a stable version of React yet because we are still working on several intertwined framework-only features (such as [asset loading](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023)) and expect more breaking changes there.
This means that React Server Components are ready to be adopted by frameworks. However, until the next major React release, the only way for a framework to adopt them is to ship a pinned Canary version of React. (To avoid bundling two copies of React, frameworks that wish to do this would need to enforce resolution of `react` and `react-dom` to the pinned Canary they ship with their framework, and explain that to their users. As an example, this is what Next.js App Router does.)
## Testing libraries against both Stable and Canary versions[Link for Testing libraries against both Stable and Canary versions]()
We do not expect library authors to test every single Canary release since it would be prohibitively difficult. However, just as when we [originally introduced the different React pre-release channels three years ago](https://legacy.reactjs.org/blog/2019/10/22/react-release-channels.html), we encourage libraries to run tests against *both* the latest Stable and latest Canary versions. If you see a change in behavior that wasn’t announced, please file a bug in the React repository so that we can help diagnose it. We expect that as this practice becomes widely adopted, it will reduce the amount of effort necessary to upgrade libraries to new major versions of React, since accidental regressions would be found as they land.
### Note
Strictly speaking, Canary is not a *new* release channel—it used to be called Next. However, we’ve decided to rename it to avoid confusion with Next.js. We’re announcing it as a *new* release channel to communicate the new expectations, such as Canaries being an officially supported way to use React.
## Stable releases work like before[Link for Stable releases work like before]()
We are not introducing any changes to stable React releases.
[PreviousReact Labs: What We've Been Working On – February 2024](https://react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024)
[NextReact Labs: What We've Been Working On – March 2023](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023) |
https://react.dev/reference/rsc/use-client | [API Reference](https://react.dev/reference/react)
[Directives](https://react.dev/reference/rsc/directives)
# 'use client'[Link for this heading]()
### React Server Components
`'use client'` is for use with [React Server Components](https://react.dev/learn/start-a-new-react-project).
`'use client'` lets you mark what code runs on the client.
- [Reference]()
- [`'use client'`]()
- [How `'use client'` marks client code]()
- [When to use `'use client'`]()
- [Serializable types returned by Server Components]()
- [Usage]()
- [Building with interactivity and state]()
- [Using client APIs]()
- [Using third-party libraries]()
* * *
## Reference[Link for Reference]()
### `'use client'`[Link for this heading]()
Add `'use client'` at the top of a file to mark the module and its transitive dependencies as client code.
```
'use client';
import { useState } from 'react';
import { formatDate } from './formatters';
import Button from './button';
export default function RichTextEditor({ timestamp, text }) {
const date = formatDate(timestamp);
// ...
const editButton = <Button />;
// ...
}
```
When a file marked with `'use client'` is imported from a Server Component, [compatible bundlers](https://react.dev/learn/start-a-new-react-project) will treat the module import as a boundary between server-run and client-run code.
As dependencies of `RichTextEditor`, `formatDate` and `Button` will also be evaluated on the client regardless of whether their modules contain a `'use client'` directive. Note that a single module may be evaluated on the server when imported from server code and on the client when imported from client code.
#### Caveats[Link for Caveats]()
- `'use client'` must be at the very beginning of a file, above any imports or other code (comments are OK). They must be written with single or double quotes, but not backticks.
- When a `'use client'` module is imported from another client-rendered module, the directive has no effect.
- When a component module contains a `'use client'` directive, any usage of that component is guaranteed to be a Client Component. However, a component can still be evaluated on the client even if it does not have a `'use client'` directive.
- A component usage is considered a Client Component if it is defined in module with `'use client'` directive or when it is a transitive dependency of a module that contains a `'use client'` directive. Otherwise, it is a Server Component.
- Code that is marked for client evaluation is not limited to components. All code that is a part of the Client module sub-tree is sent to and run by the client.
- When a server evaluated module imports values from a `'use client'` module, the values must either be a React component or [supported serializable prop values]() to be passed to a Client Component. Any other use case will throw an exception.
### How `'use client'` marks client code[Link for this heading]()
In a React app, components are often split into separate files, or [modules](https://react.dev/learn/importing-and-exporting-components).
For apps that use React Server Components, the app is server-rendered by default. `'use client'` introduces a server-client boundary in the [module dependency tree](https://react.dev/learn/understanding-your-ui-as-a-tree), effectively creating a subtree of Client modules.
To better illustrate this, consider the following React Server Components app.
App.jsFancyText.jsInspirationGenerator.jsCopyright.jsinspirations.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import FancyText from './FancyText';
import InspirationGenerator from './InspirationGenerator';
import Copyright from './Copyright';
export default function App() {
return (
<>
<FancyText title text="Get Inspired App" />
<InspirationGenerator>
<Copyright year={2004} />
</InspirationGenerator>
</>
);
}
```
In the module dependency tree of this example app, the `'use client'` directive in `InspirationGenerator.js` marks that module and all of its transitive dependencies as Client modules. The subtree starting at `InspirationGenerator.js` is now marked as Client modules.
![A tree graph with the top node representing the module 'App.js'. 'App.js' has three children: 'Copyright.js', 'FancyText.js', and 'InspirationGenerator.js'. 'InspirationGenerator.js' has two children: 'FancyText.js' and 'inspirations.js'. The nodes under and including 'InspirationGenerator.js' have a yellow background color to signify that this sub-graph is client-rendered due to the 'use client' directive in 'InspirationGenerator.js'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_module_dependency.dark.png&w=1200&q=75)
![A tree graph with the top node representing the module 'App.js'. 'App.js' has three children: 'Copyright.js', 'FancyText.js', and 'InspirationGenerator.js'. 'InspirationGenerator.js' has two children: 'FancyText.js' and 'inspirations.js'. The nodes under and including 'InspirationGenerator.js' have a yellow background color to signify that this sub-graph is client-rendered due to the 'use client' directive in 'InspirationGenerator.js'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_module_dependency.png&w=1200&q=75)
`'use client'` segments the module dependency tree of the React Server Components app, marking `InspirationGenerator.js` and all of its dependencies as client-rendered.
During render, the framework will server-render the root component and continue through the [render tree](https://react.dev/learn/understanding-your-ui-as-a-tree), opting-out of evaluating any code imported from client-marked code.
The server-rendered portion of the render tree is then sent to the client. The client, with its client code downloaded, then completes rendering the rest of the tree.
![A tree graph where each node represents a component and its children as child components. The top-level node is labelled 'App' and it has two child components 'InspirationGenerator' and 'FancyText'. 'InspirationGenerator' has two child components, 'FancyText' and 'Copyright'. Both 'InspirationGenerator' and its child component 'FancyText' are marked to be client-rendered.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_render_tree.dark.png&w=1080&q=75)
![A tree graph where each node represents a component and its children as child components. The top-level node is labelled 'App' and it has two child components 'InspirationGenerator' and 'FancyText'. 'InspirationGenerator' has two child components, 'FancyText' and 'Copyright'. Both 'InspirationGenerator' and its child component 'FancyText' are marked to be client-rendered.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_render_tree.png&w=1080&q=75)
The render tree for the React Server Components app. `InspirationGenerator` and its child component `FancyText` are components exported from client-marked code and considered Client Components.
We introduce the following definitions:
- **Client Components** are components in a render tree that are rendered on the client.
- **Server Components** are components in a render tree that are rendered on the server.
Working through the example app, `App`, `FancyText` and `Copyright` are all server-rendered and considered Server Components. As `InspirationGenerator.js` and its transitive dependencies are marked as client code, the component `InspirationGenerator` and its child component `FancyText` are Client Components.
##### Deep Dive
#### How is `FancyText` both a Server and a Client Component?[Link for this heading]()
Show Details
By the above definitions, the component `FancyText` is both a Server and Client Component, how can that be?
First, let’s clarify that the term “component” is not very precise. Here are just two ways “component” can be understood:
1. A “component” can refer to a **component definition**. In most cases this will be a function.
```
// This is a definition of a component
function MyComponent() {
return <p>My Component</p>
}
```
2. A “component” can also refer to a **component usage** of its definition.
```
import MyComponent from './MyComponent';
function App() {
// This is a usage of a component
return <MyComponent />;
}
```
Often, the imprecision is not important when explaining concepts, but in this case it is.
When we talk about Server or Client Components, we are referring to component usages.
- If the component is defined in a module with a `'use client'` directive, or the component is imported and called in a Client Component, then the component usage is a Client Component.
- Otherwise, the component usage is a Server Component.
![A tree graph where each node represents a component and its children as child components. The top-level node is labelled 'App' and it has two child components 'InspirationGenerator' and 'FancyText'. 'InspirationGenerator' has two child components, 'FancyText' and 'Copyright'. Both 'InspirationGenerator' and its child component 'FancyText' are marked to be client-rendered.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_render_tree.dark.png&w=1080&q=75)
![A tree graph where each node represents a component and its children as child components. The top-level node is labelled 'App' and it has two child components 'InspirationGenerator' and 'FancyText'. 'InspirationGenerator' has two child components, 'FancyText' and 'Copyright'. Both 'InspirationGenerator' and its child component 'FancyText' are marked to be client-rendered.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_render_tree.png&w=1080&q=75)
A render tree illustrates component usages.
Back to the question of `FancyText`, we see that the component definition does *not* have a `'use client'` directive and it has two usages.
The usage of `FancyText` as a child of `App`, marks that usage as a Server Component. When `FancyText` is imported and called under `InspirationGenerator`, that usage of `FancyText` is a Client Component as `InspirationGenerator` contains a `'use client'` directive.
This means that the component definition for `FancyText` will both be evaluated on the server and also downloaded by the client to render its Client Component usage.
##### Deep Dive
#### Why is `Copyright` a Server Component?[Link for this heading]()
Show Details
Because `Copyright` is rendered as a child of the Client Component `InspirationGenerator`, you might be surprised that it is a Server Component.
Recall that `'use client'` defines the boundary between server and client code on the *module dependency tree*, not the render tree.
![A tree graph with the top node representing the module 'App.js'. 'App.js' has three children: 'Copyright.js', 'FancyText.js', and 'InspirationGenerator.js'. 'InspirationGenerator.js' has two children: 'FancyText.js' and 'inspirations.js'. The nodes under and including 'InspirationGenerator.js' have a yellow background color to signify that this sub-graph is client-rendered due to the 'use client' directive in 'InspirationGenerator.js'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_module_dependency.dark.png&w=1080&q=75)
![A tree graph with the top node representing the module 'App.js'. 'App.js' has three children: 'Copyright.js', 'FancyText.js', and 'InspirationGenerator.js'. 'InspirationGenerator.js' has two children: 'FancyText.js' and 'inspirations.js'. The nodes under and including 'InspirationGenerator.js' have a yellow background color to signify that this sub-graph is client-rendered due to the 'use client' directive in 'InspirationGenerator.js'.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fuse_client_module_dependency.png&w=1080&q=75)
`'use client'` defines the boundary between server and client code on the module dependency tree.
In the module dependency tree, we see that `App.js` imports and calls `Copyright` from the `Copyright.js` module. As `Copyright.js` does not contain a `'use client'` directive, the component usage is rendered on the server. `App` is rendered on the server as it is the root component.
Client Components can render Server Components because you can pass JSX as props. In this case, `InspirationGenerator` receives `Copyright` as [children](https://react.dev/learn/passing-props-to-a-component). However, the `InspirationGenerator` module never directly imports the `Copyright` module nor calls the component, all of that is done by `App`. In fact, the `Copyright` component is fully executed before `InspirationGenerator` starts rendering.
The takeaway is that a parent-child render relationship between components does not guarantee the same render environment.
### When to use `'use client'`[Link for this heading]()
With `'use client'`, you can determine when components are Client Components. As Server Components are default, here is a brief overview of the advantages and limitations to Server Components to determine when you need to mark something as client rendered.
For simplicity, we talk about Server Components, but the same principles apply to all code in your app that is server run.
#### Advantages of Server Components[Link for Advantages of Server Components]()
- Server Components can reduce the amount of code sent and run by the client. Only Client modules are bundled and evaluated by the client.
- Server Components benefit from running on the server. They can access the local filesystem and may experience low latency for data fetches and network requests.
#### Limitations of Server Components[Link for Limitations of Server Components]()
- Server Components cannot support interaction as event handlers must be registered and triggered by a client.
- For example, event handlers like `onClick` can only be defined in Client Components.
- Server Components cannot use most Hooks.
- When Server Components are rendered, their output is essentially a list of components for the client to render. Server Components do not persist in memory after render and cannot have their own state.
### Serializable types returned by Server Components[Link for Serializable types returned by Server Components]()
As in any React app, parent components pass data to child components. As they are rendered in different environments, passing data from a Server Component to a Client Component requires extra consideration.
Prop values passed from a Server Component to Client Component must be serializable.
Serializable props include:
- Primitives
- [string](https://developer.mozilla.org/en-US/docs/Glossary/String)
- [number](https://developer.mozilla.org/en-US/docs/Glossary/Number)
- [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
- [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
- [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)
- [null](https://developer.mozilla.org/en-US/docs/Glossary/Null)
- [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), only symbols registered in the global Symbol registry via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for)
- Iterables containing serializable values
- [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
- [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
- [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
- [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) and [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
- [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
- Plain [objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object): those created with [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), with serializable properties
- Functions that are [Server Functions](https://react.dev/reference/rsc/server-functions)
- Client or Server Component elements (JSX)
- [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Notably, these are not supported:
- [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) that are not exported from client-marked modules or marked with [`'use server'`](https://react.dev/reference/rsc/use-server)
- [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript)
- Objects that are instances of any class (other than the built-ins mentioned) or objects with [a null prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- Symbols not registered globally, ex. `Symbol('my new symbol')`
## Usage[Link for Usage]()
### Building with interactivity and state[Link for Building with interactivity and state]()
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
'use client';
import { useState } from 'react';
export default function Counter({initialValue = 0}) {
const [countValue, setCountValue] = useState(initialValue);
const increment = () => setCountValue(countValue + 1);
const decrement = () => setCountValue(countValue - 1);
return (
<>
<h2>Count Value: {countValue}</h2>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
</>
);
}
```
Show more
As `Counter` requires both the `useState` Hook and event handlers to increment or decrement the value, this component must be a Client Component and will require a `'use client'` directive at the top.
In contrast, a component that renders UI without interaction will not need to be a Client Component.
```
import { readFile } from 'node:fs/promises';
import Counter from './Counter';
export default async function CounterContainer() {
const initialValue = await readFile('/path/to/counter_value');
return <Counter initialValue={initialValue} />
}
```
For example, `Counter`’s parent component, `CounterContainer`, does not require `'use client'` as it is not interactive and does not use state. In addition, `CounterContainer` must be a Server Component as it reads from the local file system on the server, which is possible only in a Server Component.
There are also components that don’t use any server or client-only features and can be agnostic to where they render. In our earlier example, `FancyText` is one such component.
```
export default function FancyText({title, text}) {
return title
? <h1 className='fancy title'>{text}</h1>
: <h3 className='fancy cursive'>{text}</h3>
}
```
In this case, we don’t add the `'use client'` directive, resulting in `FancyText`’s *output* (rather than its source code) to be sent to the browser when referenced from a Server Component. As demonstrated in the earlier Inspirations app example, `FancyText` is used as both a Server or Client Component, depending on where it is imported and used.
But if `FancyText`’s HTML output was large relative to its source code (including dependencies), it might be more efficient to force it to always be a Client Component. Components that return a long SVG path string are one case where it may be more efficient to force a component to be a Client Component.
### Using client APIs[Link for Using client APIs]()
Your React app may use client-specific APIs, such as the browser’s APIs for web storage, audio and video manipulation, and device hardware, among [others](https://developer.mozilla.org/en-US/docs/Web/API).
In this example, the component uses [DOM APIs](https://developer.mozilla.org/en-US/docs/Glossary/DOM) to manipulate a [`canvas`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element. Since those APIs are only available in the browser, it must be marked as a Client Component.
```
'use client';
import {useRef, useEffect} from 'react';
export default function Circle() {
const ref = useRef(null);
useLayoutEffect(() => {
const canvas = ref.current;
const context = canvas.getContext('2d');
context.reset();
context.beginPath();
context.arc(100, 75, 50, 0, 2 * Math.PI);
context.stroke();
});
return <canvas ref={ref} />;
}
```
### Using third-party libraries[Link for Using third-party libraries]()
Often in a React app, you’ll leverage third-party libraries to handle common UI patterns or logic.
These libraries may rely on component Hooks or client APIs. Third-party components that use any of the following React APIs must run on the client:
- [createContext](https://react.dev/reference/react/createContext)
- [`react`](https://react.dev/reference/react/hooks) and [`react-dom`](https://react.dev/reference/react-dom/hooks) Hooks, excluding [`use`](https://react.dev/reference/react/use) and [`useId`](https://react.dev/reference/react/useId)
- [forwardRef](https://react.dev/reference/react/forwardRef)
- [memo](https://react.dev/reference/react/memo)
- [startTransition](https://react.dev/reference/react/startTransition)
- If they use client APIs, ex. DOM insertion or native platform views
If these libraries have been updated to be compatible with React Server Components, then they will already include `'use client'` markers of their own, allowing you to use them directly from your Server Components. If a library hasn’t been updated, or if a component needs props like event handlers that can only be specified on the client, you may need to add your own Client Component file in between the third-party Client Component and your Server Component where you’d like to use it.
[PreviousDirectives](https://react.dev/reference/rsc/directives)
[Next'use server'](https://react.dev/reference/rsc/use-server) |
https://react.dev/reference/react-dom/server/renderToStaticMarkup | [API Reference](https://react.dev/reference/react)
[Server APIs](https://react.dev/reference/react-dom/server)
# renderToStaticMarkup[Link for this heading]()
`renderToStaticMarkup` renders a non-interactive React tree to an HTML string.
```
const html = renderToStaticMarkup(reactNode, options?)
```
- [Reference]()
- [`renderToStaticMarkup(reactNode, options?)`]()
- [Usage]()
- [Rendering a non-interactive React tree as HTML to a string]()
* * *
## Reference[Link for Reference]()
### `renderToStaticMarkup(reactNode, options?)`[Link for this heading]()
On the server, call `renderToStaticMarkup` to render your app to HTML.
```
import { renderToStaticMarkup } from 'react-dom/server';
const html = renderToStaticMarkup(<Page />);
```
It will produce non-interactive HTML output of your React components.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `reactNode`: A React node you want to render to HTML. For example, a JSX node like `<Page />`.
- **optional** `options`: An object for server render.
- **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](https://react.dev/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page.
#### Returns[Link for Returns]()
An HTML string.
#### Caveats[Link for Caveats]()
- `renderToStaticMarkup` output cannot be hydrated.
- `renderToStaticMarkup` has limited Suspense support. If a component suspends, `renderToStaticMarkup` immediately sends its fallback as HTML.
- `renderToStaticMarkup` works in the browser, but using it in the client code is not recommended. If you need to render a component to HTML in the browser, [get the HTML by rendering it into a DOM node.](https://react.dev/reference/react-dom/server/renderToString)
* * *
## Usage[Link for Usage]()
### Rendering a non-interactive React tree as HTML to a string[Link for Rendering a non-interactive React tree as HTML to a string]()
Call `renderToStaticMarkup` to render your app to an HTML string which you can send with your server response:
```
import { renderToStaticMarkup } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const html = renderToStaticMarkup(<Page />);
response.send(html);
});
```
This will produce the initial non-interactive HTML output of your React components.
### Pitfall
This method renders **non-interactive HTML that cannot be hydrated.** This is useful if you want to use React as a simple static page generator, or if you’re rendering completely static content like emails.
Interactive apps should use [`renderToString`](https://react.dev/reference/react-dom/server/renderToString) on the server and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) on the client.
[PreviousrenderToReadableStream](https://react.dev/reference/react-dom/server/renderToReadableStream)
[NextrenderToString](https://react.dev/reference/react-dom/server/renderToString) |
https://react.dev/reference/react-dom/server/renderToString | [API Reference](https://react.dev/reference/react)
[Server APIs](https://react.dev/reference/react-dom/server)
# renderToString[Link for this heading]()
### Pitfall
`renderToString` does not support streaming or waiting for data. [See the alternatives.]()
`renderToString` renders a React tree to an HTML string.
```
const html = renderToString(reactNode, options?)
```
- [Reference]()
- [`renderToString(reactNode, options?)`]()
- [Usage]()
- [Rendering a React tree as HTML to a string]()
- [Alternatives]()
- [Migrating from `renderToString` to a streaming render on the server]()
- [Migrating from `renderToString` to a static prerender on the server]()
- [Removing `renderToString` from the client code]()
- [Troubleshooting]()
- [When a component suspends, the HTML always contains a fallback]()
* * *
## Reference[Link for Reference]()
### `renderToString(reactNode, options?)`[Link for this heading]()
On the server, call `renderToString` to render your app to HTML.
```
import { renderToString } from 'react-dom/server';
const html = renderToString(<App />);
```
On the client, call [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `reactNode`: A React node you want to render to HTML. For example, a JSX node like `<App />`.
- **optional** `options`: An object for server render.
- **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](https://react.dev/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](https://react.dev/reference/react-dom/client/hydrateRoot)
#### Returns[Link for Returns]()
An HTML string.
#### Caveats[Link for Caveats]()
- `renderToString` has limited Suspense support. If a component suspends, `renderToString` immediately sends its fallback as HTML.
- `renderToString` works in the browser, but using it in the client code is [not recommended.]()
* * *
## Usage[Link for Usage]()
### Rendering a React tree as HTML to a string[Link for Rendering a React tree as HTML to a string]()
Call `renderToString` to render your app to an HTML string which you can send with your server response:
```
import { renderToString } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const html = renderToString(<App />);
response.send(html);
});
```
This will produce the initial non-interactive HTML output of your React components. On the client, you will need to call [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) to *hydrate* that server-generated HTML and make it interactive.
### Pitfall
`renderToString` does not support streaming or waiting for data. [See the alternatives.]()
* * *
## Alternatives[Link for Alternatives]()
### Migrating from `renderToString` to a streaming render on the server[Link for this heading]()
`renderToString` returns a string immediately, so it does not support streaming content as it loads.
When possible, we recommend using these fully-featured alternatives:
- If you use Node.js, use [`renderToPipeableStream`.](https://react.dev/reference/react-dom/server/renderToPipeableStream)
- If you use Deno or a modern edge runtime with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), use [`renderToReadableStream`.](https://react.dev/reference/react-dom/server/renderToReadableStream)
You can continue using `renderToString` if your server environment does not support streams.
* * *
### Migrating from `renderToString` to a static prerender on the server[Link for this heading]()
`renderToString` returns a string immediately, so it does not support waiting for data to load for static HTML generation.
We recommend using these fully-featured alternatives:
- If you use Node.js, use [`prerenderToNodeStream`.](https://react.dev/reference/react-dom/static/prerenderToNodeStream)
- If you use Deno or a modern edge runtime with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), use [`prerender`.](https://react.dev/reference/react-dom/static/prerender)
You can continue using `renderToString` if your static site generation environment does not support streams.
* * *
### Removing `renderToString` from the client code[Link for this heading]()
Sometimes, `renderToString` is used on the client to convert some component to HTML.
```
// 🚩 Unnecessary: using renderToString on the client
import { renderToString } from 'react-dom/server';
const html = renderToString(<MyIcon />);
console.log(html); // For example, "<svg>...</svg>"
```
Importing `react-dom/server` **on the client** unnecessarily increases your bundle size and should be avoided. If you need to render some component to HTML in the browser, use [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and read HTML from the DOM:
```
import { createRoot } from 'react-dom/client';
import { flushSync } from 'react-dom';
const div = document.createElement('div');
const root = createRoot(div);
flushSync(() => {
root.render(<MyIcon />);
});
console.log(div.innerHTML); // For example, "<svg>...</svg>"
```
The [`flushSync`](https://react.dev/reference/react-dom/flushSync) call is necessary so that the DOM is updated before reading its [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) property.
* * *
## Troubleshooting[Link for Troubleshooting]()
### When a component suspends, the HTML always contains a fallback[Link for When a component suspends, the HTML always contains a fallback]()
`renderToString` does not fully support Suspense.
If some component suspends (for example, because it’s defined with [`lazy`](https://react.dev/reference/react/lazy) or fetches data), `renderToString` will not wait for its content to resolve. Instead, `renderToString` will find the closest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary above it and render its `fallback` prop in the HTML. The content will not appear until the client code loads.
To solve this, use one of the [recommended streaming solutions.]() For server side rendering, they can stream content in chunks as it resolves on the server so that the user sees the page being progressively filled in before the client code loads. For static site generation, they can wait for all the content to resolve before generating the static HTML.
[PreviousrenderToStaticMarkup](https://react.dev/reference/react-dom/server/renderToStaticMarkup)
[NextStatic APIs](https://react.dev/reference/react-dom/static) |
https://react.dev/reference/react-dom/server/renderToReadableStream | [API Reference](https://react.dev/reference/react)
[Server APIs](https://react.dev/reference/react-dom/server)
# renderToReadableStream[Link for this heading]()
`renderToReadableStream` renders a React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
```
const stream = await renderToReadableStream(reactNode, options?)
```
- [Reference]()
- [`renderToReadableStream(reactNode, options?)`]()
- [Usage]()
- [Rendering a React tree as HTML to a Readable Web Stream]()
- [Streaming more content as it loads]()
- [Specifying what goes into the shell]()
- [Logging crashes on the server]()
- [Recovering from errors inside the shell]()
- [Recovering from errors outside the shell]()
- [Setting the status code]()
- [Handling different errors in different ways]()
- [Waiting for all content to load for crawlers and static generation]()
- [Aborting server rendering]()
### Note
This API depends on [Web Streams.](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) For Node.js, use [`renderToPipeableStream`](https://react.dev/reference/react-dom/server/renderToPipeableStream) instead.
* * *
## Reference[Link for Reference]()
### `renderToReadableStream(reactNode, options?)`[Link for this heading]()
Call `renderToReadableStream` to render your React tree as HTML into a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
```
import { renderToReadableStream } from 'react-dom/server';
async function handler(request) {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
On the client, call [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
[See more examples below.]()
#### Parameters[Link for Parameters]()
- `reactNode`: A React node you want to render to HTML. For example, a JSX element like `<App />`. It is expected to represent the entire document, so the `App` component should render the `<html>` tag.
- **optional** `options`: An object with streaming options.
- **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline `<script>` tag.
- **optional** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](https://react.dev/reference/react-dom/client/hydrateRoot) Omit it if you don’t want to run React on the client at all.
- **optional** `bootstrapModules`: Like `bootstrapScripts`, but emits [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) instead.
- **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](https://react.dev/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](https://react.dev/reference/react-dom/client/hydrateRoot)
- **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
- **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
- **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable]() or [not.]() By default, this only calls `console.error`. If you override it to [log crash reports,]() make sure that you still call `console.error`. You can also use it to [adjust the status code]() before the shell is emitted.
- **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js)
- **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering]() and render the rest on the client.
#### Returns[Link for Returns]()
`renderToReadableStream` returns a Promise:
- If rendering the [shell]() is successful, that Promise will resolve to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
- If rendering the shell fails, the Promise will be rejected. [Use this to output a fallback shell.]()
The returned stream has an additional property:
- `allReady`: A Promise that resolves when all rendering is complete, including both the [shell]() and all additional [content.]() You can `await stream.allReady` before returning a response [for crawlers and static generation.]() If you do that, you won’t get any progressive loading. The stream will contain the final HTML.
* * *
## Usage[Link for Usage]()
### Rendering a React tree as HTML to a Readable Web Stream[Link for Rendering a React tree as HTML to a Readable Web Stream]()
Call `renderToReadableStream` to render your React tree as HTML into a [Readable Web Stream:](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
```
import { renderToReadableStream } from 'react-dom/server';
async function handler(request) {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
Along with the root component, you need to provide a list of bootstrap `<script>` paths. Your root component should return **the entire document including the root `<html>` tag.**
For example, it might look like this:
```
export default function App() {
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/styles.css"></link>
<title>My app</title>
</head>
<body>
<Router />
</body>
</html>
);
}
```
React will inject the [doctype](https://developer.mozilla.org/en-US/docs/Glossary/Doctype) and your bootstrap `<script>` tags into the resulting HTML stream:
```
<!DOCTYPE html>
<html>
<!-- ... HTML from your components ... -->
</html>
<script src="/main.js" async=""></script>
```
On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](https://react.dev/reference/react-dom/client/hydrateRoot)
```
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);
```
This will attach event listeners to the server-generated HTML and make it interactive.
##### Deep Dive
#### Reading CSS and JS asset paths from the build output[Link for Reading CSS and JS asset paths from the build output]()
Show Details
The final asset URLs (like JavaScript and CSS files) are often hashed after the build. For example, instead of `styles.css` you might end up with `styles.123456.css`. Hashing static asset filenames guarantees that every distinct build of the same asset will have a different filename. This is useful because it lets you safely enable long-term caching for static assets: a file with a certain name would never change content.
However, if you don’t know the asset URLs until after the build, there’s no way for you to put them in the source code. For example, hardcoding `"/styles.css"` into JSX like earlier wouldn’t work. To keep them out of your source code, your root component can read the real filenames from a map passed as a prop:
```
export default function App({ assetMap }) {
return (
<html>
<head>
<title>My app</title>
<link rel="stylesheet" href={assetMap['styles.css']}></link>
</head>
...
</html>
);
}
```
On the server, render `<App assetMap={assetMap} />` and pass your `assetMap` with the asset URLs:
```
// You'd need to get this JSON from your build tooling, e.g. read it from the build output.
const assetMap = {
'styles.css': '/styles.123456.css',
'main.js': '/main.123456.js'
};
async function handler(request) {
const stream = await renderToReadableStream(<App assetMap={assetMap} />, {
bootstrapScripts: [assetMap['/main.js']]
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
Since your server is now rendering `<App assetMap={assetMap} />`, you need to render it with `assetMap` on the client too to avoid hydration errors. You can serialize and pass `assetMap` to the client like this:
```
// You'd need to get this JSON from your build tooling.
const assetMap = {
'styles.css': '/styles.123456.css',
'main.js': '/main.123456.js'
};
async function handler(request) {
const stream = await renderToReadableStream(<App assetMap={assetMap} />, {
// Careful: It's safe to stringify() this because this data isn't user-generated.
bootstrapScriptContent: `window.assetMap = ${JSON.stringify(assetMap)};`,
bootstrapScripts: [assetMap['/main.js']],
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
In the example above, the `bootstrapScriptContent` option adds an extra inline `<script>` tag that sets the global `window.assetMap` variable on the client. This lets the client code read the same `assetMap`:
```
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App assetMap={window.assetMap} />);
```
Both client and server render `App` with the same `assetMap` prop, so there are no hydration errors.
* * *
### Streaming more content as it loads[Link for Streaming more content as it loads]()
Streaming allows the user to start seeing the content even before all the data has loaded on the server. For example, consider a profile page that shows a cover, a sidebar with friends and photos, and a list of posts:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Posts />
</ProfileLayout>
);
}
```
Imagine that loading data for `<Posts />` takes some time. Ideally, you’d want to show the rest of the profile page content to the user without waiting for the posts. To do this, [wrap `Posts` in a `<Suspense>` boundary:](https://react.dev/reference/react/Suspense)
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
```
This tells React to start streaming the HTML before `Posts` loads its data. React will send the HTML for the loading fallback (`PostsGlimmer`) first, and then, when `Posts` finishes loading its data, React will send the remaining HTML along with an inline `<script>` tag that replaces the loading fallback with that HTML. From the user’s perspective, the page will first appear with the `PostsGlimmer`, later replaced by the `Posts`.
You can further [nest `<Suspense>` boundaries](https://react.dev/reference/react/Suspense) to create a more granular loading sequence:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<BigSpinner />}>
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</Suspense>
</ProfileLayout>
);
}
```
In this example, React can start streaming the page even earlier. Only `ProfileLayout` and `ProfileCover` must finish rendering first because they are not wrapped in any `<Suspense>` boundary. However, if `Sidebar`, `Friends`, or `Photos` need to load some data, React will send the HTML for the `BigSpinner` fallback instead. Then, as more data becomes available, more content will continue to be revealed until all of it becomes visible.
Streaming does not need to wait for React itself to load in the browser, or for your app to become interactive. The HTML content from the server will get progressively revealed before any of the `<script>` tags load.
[Read more about how streaming HTML works.](https://github.com/reactwg/react-18/discussions/37)
### Note
**Only Suspense-enabled data sources will activate the Suspense component.** They include:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/getting-started/react-essentials)
- Lazy-loading component code with [`lazy`](https://react.dev/reference/react/lazy)
- Reading the value of a Promise with [`use`](https://react.dev/reference/react/use)
Suspense **does not** detect when data is fetched inside an Effect or event handler.
The exact way you would load data in the `Posts` component above depends on your framework. If you use a Suspense-enabled framework, you’ll find the details in its data fetching documentation.
Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React.
* * *
### Specifying what goes into the shell[Link for Specifying what goes into the shell]()
The part of your app outside of any `<Suspense>` boundaries is called *the shell:*
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<BigSpinner />}>
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</Suspense>
</ProfileLayout>
);
}
```
It determines the earliest loading state that the user may see:
```
<ProfileLayout>
<ProfileCover />
<BigSpinner />
</ProfileLayout>
```
If you wrap the whole app into a `<Suspense>` boundary at the root, the shell will only contain that spinner. However, that’s not a pleasant user experience because seeing a big spinner on the screen can feel slower and more annoying than waiting a bit more and seeing the real layout. This is why usually you’ll want to place the `<Suspense>` boundaries so that the shell feels *minimal but complete*—like a skeleton of the entire page layout.
The async call to `renderToReadableStream` will resolve to a `stream` as soon as the entire shell has been rendered. Usually, you’ll start streaming then by creating and returning a response with that `stream`:
```
async function handler(request) {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
By the time the `stream` is returned, components in nested `<Suspense>` boundaries might still be loading data.
* * *
### Logging crashes on the server[Link for Logging crashes on the server]()
By default, all errors on the server are logged to console. You can override this behavior to log crash reports:
```
async function handler(request) {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
console.error(error);
logServerCrashReport(error);
}
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
If you provide a custom `onError` implementation, don’t forget to also log errors to the console like above.
* * *
### Recovering from errors inside the shell[Link for Recovering from errors inside the shell]()
In this example, the shell contains `ProfileLayout`, `ProfileCover`, and `PostsGlimmer`:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
```
If an error occurs while rendering those components, React won’t have any meaningful HTML to send to the client. Wrap your `renderToReadableStream` call in a `try...catch` to send a fallback HTML that doesn’t rely on server rendering as the last resort:
```
async function handler(request) {
try {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
console.error(error);
logServerCrashReport(error);
}
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: 500,
headers: { 'content-type': 'text/html' },
});
}
}
```
If there is an error while generating the shell, both `onError` and your `catch` block will fire. Use `onError` for error reporting and use the `catch` block to send the fallback HTML document. Your fallback HTML does not have to be an error page. Instead, you may include an alternative shell that renders your app on the client only.
* * *
### Recovering from errors outside the shell[Link for Recovering from errors outside the shell]()
In this example, the `<Posts />` component is wrapped in `<Suspense>` so it is *not* a part of the shell:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
```
If an error happens in the `Posts` component or somewhere inside it, React will [try to recover from it:](https://react.dev/reference/react/Suspense)
1. It will emit the loading fallback for the closest `<Suspense>` boundary (`PostsGlimmer`) into the HTML.
2. It will “give up” on trying to render the `Posts` content on the server anymore.
3. When the JavaScript code loads on the client, React will *retry* rendering `Posts` on the client.
If retrying rendering `Posts` on the client *also* fails, React will throw the error on the client. As with all the errors thrown during rendering, the [closest parent error boundary](https://react.dev/reference/react/Component) determines how to present the error to the user. In practice, this means that the user will see a loading indicator until it is certain that the error is not recoverable.
If retrying rendering `Posts` on the client succeeds, the loading fallback from the server will be replaced with the client rendering output. The user will not know that there was a server error. However, the server `onError` callback and the client [`onRecoverableError`](https://react.dev/reference/react-dom/client/hydrateRoot) callbacks will fire so that you can get notified about the error.
* * *
### Setting the status code[Link for Setting the status code]()
Streaming introduces a tradeoff. You want to start streaming the page as early as possible so that the user can see the content sooner. However, once you start streaming, you can no longer set the response status code.
By [dividing your app]() into the shell (above all `<Suspense>` boundaries) and the rest of the content, you’ve already solved a part of this problem. If the shell errors, your `catch` block will run which lets you set the error status code. Otherwise, you know that the app may recover on the client, so you can send “OK”.
```
async function handler(request) {
try {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
console.error(error);
logServerCrashReport(error);
}
});
return new Response(stream, {
status: 200,
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: 500,
headers: { 'content-type': 'text/html' },
});
}
}
```
If a component *outside* the shell (i.e. inside a `<Suspense>` boundary) throws an error, React will not stop rendering. This means that the `onError` callback will fire, but your code will continue running without getting into the `catch` block. This is because React will try to recover from that error on the client, [as described above.]()
However, if you’d like, you can use the fact that something has errored to set the status code:
```
async function handler(request) {
try {
let didError = false;
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
return new Response(stream, {
status: didError ? 500 : 200,
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: 500,
headers: { 'content-type': 'text/html' },
});
}
}
```
This will only catch errors outside the shell that happened while generating the initial shell content, so it’s not exhaustive. If knowing whether an error occurred for some content is critical, you can move it up into the shell.
* * *
### Handling different errors in different ways[Link for Handling different errors in different ways]()
You can [create your own `Error` subclasses](https://javascript.info/custom-errors) and use the [`instanceof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) operator to check which error is thrown. For example, you can define a custom `NotFoundError` and throw it from your component. Then you can save the error in `onError` and do something different before returning the response depending on the error type:
```
async function handler(request) {
let didError = false;
let caughtError = null;
function getStatusCode() {
if (didError) {
if (caughtError instanceof NotFoundError) {
return 404;
} else {
return 500;
}
} else {
return 200;
}
}
try {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
didError = true;
caughtError = error;
console.error(error);
logServerCrashReport(error);
}
});
return new Response(stream, {
status: getStatusCode(),
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: getStatusCode(),
headers: { 'content-type': 'text/html' },
});
}
}
```
Keep in mind that once you emit the shell and start streaming, you can’t change the status code.
* * *
### Waiting for all content to load for crawlers and static generation[Link for Waiting for all content to load for crawlers and static generation]()
Streaming offers a better user experience because the user can see the content as it becomes available.
However, when a crawler visits your page, or if you’re generating the pages at the build time, you might want to let all of the content load first and then produce the final HTML output instead of revealing it progressively.
You can wait for all the content to load by awaiting the `stream.allReady` Promise:
```
async function handler(request) {
try {
let didError = false;
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
let isCrawler = // ... depends on your bot detection strategy ...
if (isCrawler) {
await stream.allReady;
}
return new Response(stream, {
status: didError ? 500 : 200,
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: 500,
headers: { 'content-type': 'text/html' },
});
}
}
```
A regular visitor will get a stream of progressively loaded content. A crawler will receive the final HTML output after all the data loads. However, this also means that the crawler will have to wait for *all* data, some of which might be slow to load or error. Depending on your app, you could choose to send the shell to the crawlers too.
* * *
### Aborting server rendering[Link for Aborting server rendering]()
You can force the server rendering to “give up” after a timeout:
```
async function handler(request) {
try {
const controller = new AbortController();
setTimeout(() => {
controller.abort();
}, 10000);
const stream = await renderToReadableStream(<App />, {
signal: controller.signal,
bootstrapScripts: ['/main.js'],
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
// ...
```
React will flush the remaining loading fallbacks as HTML, and will attempt to render the rest on the client.
[PreviousrenderToPipeableStream](https://react.dev/reference/react-dom/server/renderToPipeableStream)
[NextrenderToStaticMarkup](https://react.dev/reference/react-dom/server/renderToStaticMarkup) |
https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023 | [Blog](https://react.dev/blog)
# React Labs: What We've Been Working On – March 2023[Link for this heading]()
March 22, 2023 by [Joseph Savona](https://twitter.com/en_JS), [Josh Story](https://twitter.com/joshcstory), [Lauren Tan](https://twitter.com/potetotes), [Mengdi Chen](https://twitter.com/mengdi_en), [Samuel Susla](https://twitter.com/SamuelSusla), [Sathya Gunasekaran](https://twitter.com/_gsathya), [Sebastian Markbåge](https://twitter.com/sebmarkbage), and [Andrew Clark](https://twitter.com/acdlite)
* * *
In React Labs posts, we write about projects in active research and development. We’ve made significant progress on them since our [last update](https://react.dev/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022), and we’d like to share what we learned.
* * *
## React Server Components[Link for React Server Components]()
React Server Components (or RSC) is a new application architecture designed by the React team.
We’ve first shared our research on RSC in an [introductory talk](https://react.dev/blog/2020/12/21/data-fetching-with-react-server-components) and an [RFC](https://github.com/reactjs/rfcs/pull/188). To recap them, we are introducing a new kind of component—Server Components—that run ahead of time and are excluded from your JavaScript bundle. Server Components can run during the build, letting you read from the filesystem or fetch static content. They can also run on the server, letting you access your data layer without having to build an API. You can pass data by props from Server Components to the interactive Client Components in the browser.
RSC combines the simple “request/response” mental model of server-centric Multi-Page Apps with the seamless interactivity of client-centric Single-Page Apps, giving you the best of both worlds.
Since our last update, we have merged the [React Server Components RFC](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md) to ratify the proposal. We resolved outstanding issues with the [React Server Module Conventions](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md) proposal, and reached consensus with our partners to go with the `"use client"` convention. These documents also act as specification for what an RSC-compatible implementation should support.
The biggest change is that we introduced [`async` / `await`](https://github.com/reactjs/rfcs/pull/229) as the primary way to do data fetching from Server Components. We also plan to support data loading from the client by introducing a new Hook called `use` that unwraps Promises. Although we can’t support `async / await` in arbitrary components in client-only apps, we plan to add support for it when you structure your client-only app similar to how RSC apps are structured.
Now that we have data fetching pretty well sorted, we’re exploring the other direction: sending data from the client to the server, so that you can execute database mutations and implement forms. We’re doing this by letting you pass Server Action functions across the server/client boundary, which the client can then call, providing seamless RPC. Server Actions also give you progressively enhanced forms before JavaScript loads.
React Server Components has shipped in [Next.js App Router](https://react.dev/learn/start-a-new-react-project). This showcases a deep integration of a router that really buys into RSC as a primitive, but it’s not the only way to build a RSC-compatible router and framework. There’s a clear separation for features provided by the RSC spec and implementation. React Server Components is meant as a spec for components that work across compatible React frameworks.
We generally recommend using an existing framework, but if you need to build your own custom framework, it is possible. Building your own RSC-compatible framework is not as easy as we’d like it to be, mainly due to the deep bundler integration needed. The current generation of bundlers are great for use on the client, but they weren’t designed with first-class support for splitting a single module graph between the server and the client. This is why we’re now partnering directly with bundler developers to get the primitives for RSC built-in.
## Asset Loading[Link for Asset Loading]()
[Suspense](https://react.dev/reference/react/Suspense) lets you specify what to display on the screen while the data or code for your components is still being loaded. This lets your users progressively see more content while the page is loading as well as during the router navigations that load more data and code. However, from the user’s perspective, data loading and rendering do not tell the whole story when considering whether new content is ready. By default, browsers load stylesheets, fonts, and images independently, which can lead to UI jumps and consecutive layout shifts.
We’re working to fully integrate Suspense with the loading lifecycle of stylesheets, fonts, and images, so that React takes them into account to determine whether the content is ready to be displayed. Without any change to the way you author your React components, updates will behave in a more coherent and pleasing manner. As an optimization, we will also provide a manual way to preload assets like fonts directly from components.
We are currently implementing these features and will have more to share soon.
## Document Metadata[Link for Document Metadata]()
Different pages and screens in your app may have different metadata like the `<title>` tag, description, and other `<meta>` tags specific to this screen. From the maintenance perspective, it’s more scalable to keep this information close to the React component for that page or screen. However, the HTML tags for this metadata need to be in the document `<head>` which is typically rendered in a component at the very root of your app.
Today, people solve this problem with one of the two techniques.
One technique is to render a special third-party component that moves `<title>`, `<meta>`, and other tags inside it into the document `<head>`. This works for major browsers but there are many clients which do not run client-side JavaScript, such as Open Graph parsers, and so this technique is not universally suitable.
Another technique is to server-render the page in two parts. First, the main content is rendered and all such tags are collected. Then, the `<head>` is rendered with these tags. Finally, the `<head>` and the main content are sent to the browser. This approach works, but it prevents you from taking advantage of the [React 18’s Streaming Server Renderer](https://react.dev/reference/react-dom/server/renderToReadableStream) because you’d have to wait for all content to render before sending the `<head>`.
This is why we’re adding built-in support for rendering `<title>`, `<meta>`, and metadata `<link>` tags anywhere in your component tree out of the box. It would work the same way in all environments, including fully client-side code, SSR, and in the future, RSC. We will share more details about this soon.
## React Optimizing Compiler[Link for React Optimizing Compiler]()
Since our previous update we’ve been actively iterating on the design of [React Forget](https://react.dev/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022), an optimizing compiler for React. We’ve previously talked about it as an “auto-memoizing compiler”, and that is true in some sense. But building the compiler has helped us understand React’s programming model even more deeply. A better way to understand React Forget is as an automatic *reactivity* compiler.
The core idea of React is that developers define their UI as a function of the current state. You work with plain JavaScript values — numbers, strings, arrays, objects — and use standard JavaScript idioms — if/else, for, etc — to describe your component logic. The mental model is that React will re-render whenever the application state changes. We believe this simple mental model and keeping close to JavaScript semantics is an important principle in React’s programming model.
The catch is that React can sometimes be *too* reactive: it can re-render too much. For example, in JavaScript we don’t have cheap ways to compare if two objects or arrays are equivalent (having the same keys and values), so creating a new object or array on each render may cause React to do more work than it strictly needs to. This means developers have to explicitly memoize components so as to not over-react to changes.
Our goal with React Forget is to ensure that React apps have just the right amount of reactivity by default: that apps re-render only when state values *meaningfully* change. From an implementation perspective this means automatically memoizing, but we believe that the reactivity framing is a better way to understand React and Forget. One way to think about this is that React currently re-renders when object identity changes. With Forget, React re-renders when the semantic value changes — but without incurring the runtime cost of deep comparisons.
In terms of concrete progress, since our last update we have substantially iterated on the design of the compiler to align with this automatic reactivity approach and to incorporate feedback from using the compiler internally. After some significant refactors to the compiler starting late last year, we’ve now begun using the compiler in production in limited areas at Meta. We plan to open-source it once we’ve proved it in production.
Finally, a lot of people have expressed interest in how the compiler works. We’re looking forward to sharing a lot more details when we prove the compiler and open-source it. But there are a few bits we can share now:
The core of the compiler is almost completely decoupled from Babel, and the core compiler API is (roughly) old AST in, new AST out (while retaining source location data). Under the hood we use a custom code representation and transformation pipeline in order to do low-level semantic analysis. However, the primary public interface to the compiler will be via Babel and other build system plugins. For ease of testing we currently have a Babel plugin which is a very thin wrapper that calls the compiler to generate a new version of each function and swap it in.
As we refactored the compiler over the last few months, we wanted to focus on refining the core compilation model to ensure we could handle complexities such as conditionals, loops, reassignment, and mutation. However, JavaScript has a lot of ways to express each of those features: if/else, ternaries, for, for-in, for-of, etc. Trying to support the full language up-front would have delayed the point where we could validate the core model. Instead, we started with a small but representative subset of the language: let/const, if/else, for loops, objects, arrays, primitives, function calls, and a few other features. As we gained confidence in the core model and refined our internal abstractions, we expanded the supported language subset. We’re also explicit about syntax we don’t yet support, logging diagnostics and skipping compilation for unsupported input. We have utilities to try the compiler on Meta’s codebases and see what unsupported features are most common so we can prioritize those next. We’ll continue incrementally expanding towards supporting the whole language.
Making plain JavaScript in React components reactive requires a compiler with a deep understanding of semantics so that it can understand exactly what the code is doing. By taking this approach, we’re creating a system for reactivity within JavaScript that lets you write product code of any complexity with the full expressivity of the language, instead of being limited to a domain specific language.
## Offscreen Rendering[Link for Offscreen Rendering]()
Offscreen rendering is an upcoming capability in React for rendering screens in the background without additional performance overhead. You can think of it as a version of the [`content-visibility` CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility) that works not only for DOM elements but React components, too. During our research, we’ve discovered a variety of use cases:
- A router can prerender screens in the background so that when a user navigates to them, they’re instantly available.
- A tab switching component can preserve the state of hidden tabs, so the user can switch between them without losing their progress.
- A virtualized list component can prerender additional rows above and below the visible window.
- When opening a modal or popup, the rest of the app can be put into “background” mode so that events and updates are disabled for everything except the modal.
Most React developers will not interact with React’s offscreen APIs directly. Instead, offscreen rendering will be integrated into things like routers and UI libraries, and then developers who use those libraries will automatically benefit without additional work.
The idea is that you should be able to render any React tree offscreen without changing the way you write your components. When a component is rendered offscreen, it does not actually *mount* until the component becomes visible — its effects are not fired. For example, if a component uses `useEffect` to log analytics when it appears for the first time, prerendering won’t mess up the accuracy of those analytics. Similarly, when a component goes offscreen, its effects are unmounted, too. A key feature of offscreen rendering is that you can toggle the visibility of a component without losing its state.
Since our last update, we’ve tested an experimental version of prerendering internally at Meta in our React Native apps on Android and iOS, with positive performance results. We’ve also improved how offscreen rendering works with Suspense — suspending inside an offscreen tree will not trigger Suspense fallbacks. Our remaining work involves finalizing the primitives that are exposed to library developers. We expect to publish an RFC later this year, alongside an experimental API for testing and feedback.
## Transition Tracing[Link for Transition Tracing]()
The Transition Tracing API lets you detect when [React Transitions](https://react.dev/reference/react/useTransition) become slower and investigate why they may be slow. Following our last update, we have completed the initial design of the API and published an [RFC](https://github.com/reactjs/rfcs/pull/238). The basic capabilities have also been implemented. The project is currently on hold. We welcome feedback on the RFC and look forward to resuming its development to provide a better performance measurement tool for React. This will be particularly useful with routers built on top of React Transitions, like the [Next.js App Router](https://react.dev/learn/start-a-new-react-project).
* * *
In addition to this update, our team has made recent guest appearances on community podcasts and livestreams to speak more on our work and answer questions.
- [Dan Abramov](https://twitter.com/dan_abramov) and [Joe Savona](https://twitter.com/en_JS) were interviewed by [Kent C. Dodds on his YouTube channel](https://www.youtube.com/watch?v=h7tur48JSaw), where they discussed concerns around React Server Components.
- [Dan Abramov](https://twitter.com/dan_abramov) and [Joe Savona](https://twitter.com/en_JS) were guests on the [JSParty podcast](https://jsparty.fm/267) and shared their thoughts about the future of React.
Thanks to [Andrew Clark](https://twitter.com/acdlite), [Dan Abramov](https://twitter.com/dan_abramov), [Dave McCabe](https://twitter.com/mcc_abe), [Luna Wei](https://twitter.com/lunaleaps), [Matt Carroll](https://twitter.com/mattcarrollcode), [Sean Keegan](https://twitter.com/DevRelSean), [Sebastian Silbermann](https://twitter.com/sebsilbermann), [Seth Webster](https://twitter.com/sethwebster), and [Sophie Alpert](https://twitter.com/sophiebits) for reviewing this post.
Thanks for reading, and see you in the next update!
[PreviousReact Canaries: Enabling Incremental Feature Rollout Outside Meta](https://react.dev/blog/2023/05/03/react-canaries)
[NextIntroducing react.dev](https://react.dev/blog/2023/03/16/introducing-react-dev) |
https://react.dev/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022 | [Blog](https://react.dev/blog)
# React Labs: What We've Been Working On – June 2022[Link for this heading]()
June 15, 2022 by [Andrew Clark](https://twitter.com/acdlite), [Dan Abramov](https://twitter.com/dan_abramov), [Jan Kassens](https://twitter.com/kassens), [Joseph Savona](https://twitter.com/en_JS), [Josh Story](https://twitter.com/joshcstory), [Lauren Tan](https://twitter.com/potetotes), [Luna Ruan](https://twitter.com/lunaruan), [Mengdi Chen](https://twitter.com/mengdi_en), [Rick Hanlon](https://twitter.com/rickhanlonii), [Robert Zhang](https://twitter.com/jiaxuanzhang01), [Sathya Gunasekaran](https://twitter.com/_gsathya), [Sebastian Markbåge](https://twitter.com/sebmarkbage), and [Xuan Huang](https://twitter.com/Huxpro)
* * *
[React 18](https://react.dev/blog/2022/03/29/react-v18) was years in the making, and with it brought valuable lessons for the React team. Its release was the result of many years of research and exploring many paths. Some of those paths were successful; many more were dead-ends that led to new insights. One lesson we’ve learned is that it’s frustrating for the community to wait for new features without having insight into these paths that we’re exploring.
* * *
We typically have a number of projects being worked on at any time, ranging from the more experimental to the clearly defined. Looking ahead, we’d like to start regularly sharing more about what we’ve been working on with the community across these projects.
To set expectations, this is not a roadmap with clear timelines. Many of these projects are under active research and are difficult to put concrete ship dates on. They may possibly never even ship in their current iteration depending on what we learn. Instead, we want to share with you the problem spaces we’re actively thinking about, and what we’ve learned so far.
## Server Components[Link for Server Components]()
We announced an [experimental demo of React Server Components](https://legacy.reactjs.org/blog/2020/12/21/data-fetching-with-react-server-components.html) (RSC) in December 2020. Since then we’ve been finishing up its dependencies in React 18, and working on changes inspired by experimental feedback.
In particular, we’re abandoning the idea of having forked I/O libraries (eg react-fetch), and instead adopting an async/await model for better compatibility. This doesn’t technically block RSC’s release because you can also use routers for data fetching. Another change is that we’re also moving away from the file extension approach in favor of [annotating boundaries](https://github.com/reactjs/rfcs/pull/189).
We’re working together with Vercel and Shopify to unify bundler support for shared semantics in both Webpack and Vite. Before launch, we want to make sure that the semantics of RSCs are the same across the whole React ecosystem. This is the major blocker for reaching stable.
## Asset Loading[Link for Asset Loading]()
Currently, assets like scripts, external styles, fonts, and images are typically preloaded and loaded using external systems. This can make it tricky to coordinate across new environments like streaming, Server Components, and more. We’re looking at adding APIs to preload and load deduplicated external assets through React APIs that work in all React environments.
We’re also looking at having these support Suspense so you can have images, CSS, and fonts that block display until they’re loaded but don’t block streaming and concurrent rendering. This can help avoid [“popcorning“](https://twitter.com/sebmarkbage/status/1516852731251724293) as the visuals pop and layout shifts.
## Static Server Rendering Optimizations[Link for Static Server Rendering Optimizations]()
Static Site Generation (SSG) and Incremental Static Regeneration (ISR) are great ways to get performance for cacheable pages, but we think we can add features to improve performance of dynamic Server Side Rendering (SSR) – especially when most but not all of the content is cacheable. We’re exploring ways to optimize server rendering utilizing compilation and static passes.
## React Optimizing Compiler[Link for React Optimizing Compiler]()
We gave an [early preview](https://www.youtube.com/watch?v=lGEMwh32soc) of React Forget at React Conf 2021. It’s a compiler that automatically generates the equivalent of `useMemo` and `useCallback` calls to minimize the cost of re-rendering, while retaining React’s programming model.
Recently, we finished a rewrite of the compiler to make it more reliable and capable. This new architecture allows us to analyze and memoize more complex patterns such as the use of [local mutations](https://react.dev/learn/keeping-components-pure), and opens up many new compile-time optimization opportunities beyond just being on par with memoization Hooks.
We’re also working on a playground for exploring many aspects of the compiler. While the goal of the playground is to make development of the compiler easier, we think that it will make it easier to try it out and build intuition for what the compiler does. It reveals various insights into how it works under the hood, and live renders the compiler’s outputs as you type. This will be shipped together with the compiler when it’s released.
## Offscreen[Link for Offscreen]()
Today, if you want to hide and show a component, you have two options. One is to add or remove it from the tree completely. The problem with this approach is that the state of your UI is lost each time you unmount, including state stored in the DOM, like scroll position.
The other option is to keep the component mounted and toggle the appearance visually using CSS. This preserves the state of your UI, but it comes at a performance cost, because React must keep rendering the hidden component and all of its children whenever it receives new updates.
Offscreen introduces a third option: hide the UI visually, but deprioritize its content. The idea is similar in spirit to the `content-visibility` CSS property: when content is hidden, it doesn’t need to stay in sync with the rest of the UI. React can defer the rendering work until the rest of the app is idle, or until the content becomes visible again.
Offscreen is a low level capability that unlocks high level features. Similar to React’s other concurrent features like `startTransition`, in most cases you won’t interact with the Offscreen API directly, but instead via an opinionated framework to implement patterns like:
- **Instant transitions.** Some routing frameworks already prefetch data to speed up subsequent navigations, like when hovering over a link. With Offscreen, they’ll also be able to prerender the next screen in the background.
- **Reusable state.** Similarly, when navigating between routes or tabs, you can use Offscreen to preserve the state of the previous screen so you can switch back and pick up where you left off.
- **Virtualized list rendering.** When displaying large lists of items, virtualized list frameworks will prerender more rows than are currently visible. You can use Offscreen to prerender the hidden rows at a lower priority than the visible items in the list.
- **Backgrounded content.** We’re also exploring a related feature for deprioritizing content in the background without hiding it, like when displaying a modal overlay.
## Transition Tracing[Link for Transition Tracing]()
Currently, React has two profiling tools. The [original Profiler](https://legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html) shows an overview of all the commits in a profiling session. For each commit, it also shows all components that rendered and the amount of time it took for them to render. We also have a beta version of a [Timeline Profiler](https://github.com/reactwg/react-18/discussions/76) introduced in React 18 that shows when components schedule updates and when React works on these updates. Both of these profilers help developers identify performance problems in their code.
We’ve realized that developers don’t find knowing about individual slow commits or components out of context that useful. It’s more useful to know about what actually causes the slow commits. And that developers want to be able to track specific interactions (eg a button click, an initial load, or a page navigation) to watch for performance regressions and to understand why an interaction was slow and how to fix it.
We previously tried to solve this issue by creating an [Interaction Tracing API](https://gist.github.com/bvaughn/8de925562903afd2e7a12554adcdda16), but it had some fundamental design flaws that reduced the accuracy of tracking why an interaction was slow and sometimes resulted in interactions never ending. We ended up [removing this API](https://github.com/facebook/react/pull/20037) because of these issues.
We are working on a new version for the Interaction Tracing API (tentatively called Transition Tracing because it is initiated via `startTransition`) that solves these problems.
## New React Docs[Link for New React Docs]()
Last year, we announced the beta version of the new React documentation website ([later shipped as react.dev](https://react.dev/blog/2023/03/16/introducing-react-dev)) of the new React documentation website. The new learning materials teach Hooks first and has new diagrams, illustrations, as well as many interactive examples and challenges. We took a break from that work to focus on the React 18 release, but now that React 18 is out, we’re actively working to finish and ship the new documentation.
We are currently writing a detailed section about effects, as we’ve heard that is one of the more challenging topics for both new and experienced React users. [Synchronizing with Effects](https://react.dev/learn/synchronizing-with-effects) is the first published page in the series, and there are more to come in the following weeks. When we first started writing a detailed section about effects, we’ve realized that many common effect patterns can be simplified by adding a new primitive to React. We’ve shared some initial thoughts on that in the [useEvent RFC](https://github.com/reactjs/rfcs/pull/220). It is currently in early research, and we are still iterating on the idea. We appreciate the community’s comments on the RFC so far, as well as the [feedback](https://github.com/reactjs/react.dev/issues/3308) and contributions to the ongoing documentation rewrite. We’d specifically like to thank [Harish Kumar](https://github.com/harish-sethuraman) for submitting and reviewing many improvements to the new website implementation.
*Thanks to [Sophie Alpert](https://twitter.com/sophiebits) for reviewing this blog post!*
[PreviousIntroducing react.dev](https://react.dev/blog/2023/03/16/introducing-react-dev)
[NextReact v18.0](https://react.dev/blog/2022/03/29/react-v18) |
https://react.dev/blog/2023/03/16/introducing-react-dev | [Blog](https://react.dev/blog)
# Introducing react.dev[Link for this heading]()
March 16, 2023 by [Dan Abramov](https://twitter.com/dan_abramov) and [Rachel Nabors](https://twitter.com/rachelnabors)
* * *
Today we are thrilled to launch [react.dev](https://react.dev), the new home for React and its documentation. In this post, we would like to give you a tour of the new site.
* * *
## tl;dr[Link for tl;dr]()
- The new React site ([react.dev](https://react.dev)) teaches modern React with function components and Hooks.
- We’ve included diagrams, illustrations, challenges, and over 600 new interactive examples.
- The previous React documentation site has now moved to [legacy.reactjs.org](https://legacy.reactjs.org).
## New site, new domain, new homepage[Link for New site, new domain, new homepage]()
First, a little bit of housekeeping.
To celebrate the launch of the new docs and, more importantly, to clearly separate the old and the new content, we’ve moved to the shorter [react.dev](https://react.dev) domain. The old [reactjs.org](https://reactjs.org) domain will now redirect here.
The old React docs are now archived at [legacy.reactjs.org](https://legacy.reactjs.org). All existing links to the old content will automatically redirect there to avoid “breaking the web”, but the legacy site will not get many more updates.
Believe it or not, React will soon be ten years old. In JavaScript years, it’s like a whole century! We’ve [refreshed the React homepage](https://react.dev) to reflect why we think React is a great way to create user interfaces today, and updated the getting started guides to more prominently mention modern React-based frameworks.
If you haven’t seen the new homepage yet, check it out!
## Going all-in on modern React with Hooks[Link for Going all-in on modern React with Hooks]()
When we released React Hooks in 2018, the Hooks docs assumed the reader is familiar with class components. This helped the community adopt Hooks very swiftly, but after a while the old docs failed to serve the new readers. New readers had to learn React twice: once with class components and then once again with Hooks.
**The new docs teach React with Hooks from the beginning.** The docs are divided in two main sections:
- [**Learn React**](https://react.dev/learn) is a self-paced course that teaches React from scratch.
- [**API Reference**](https://react.dev/reference) provides the details and usage examples for every React API.
Let’s have a closer look at what you can find in each section.
### Note
There are still a few rare class component use cases that do not yet have a Hook-based equivalent. Class components remain supported, and are documented in the [Legacy API](https://react.dev/reference/react/legacy) section of the new site.
## Quick start[Link for Quick start]()
The Learn section begins with the [Quick Start](https://react.dev/learn) page. It is a short introductory tour of React. It introduces the syntax for concepts like components, props, and state, but doesn’t go into much detail on how to use them.
If you like to learn by doing, we recommend checking out the [Tic-Tac-Toe Tutorial](https://react.dev/learn/tutorial-tic-tac-toe) next. It walks you through building a little game with React, while teaching the skills you’ll use every day. Here’s what you’ll build:
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
function Square({ value, onSquareClick }) {
return (
<button className="square" onClick={onSquareClick}>
{value}
</button>
);
}
function Board({ xIsNext, squares, onPlay }) {
function handleClick(i) {
if (calculateWinner(squares) || squares[i]) {
return;
}
const nextSquares = squares.slice();
if (xIsNext) {
nextSquares[i] = 'X';
} else {
nextSquares[i] = 'O';
}
onPlay(nextSquares);
}
const winner = calculateWinner(squares);
let status;
if (winner) {
status = 'Winner: ' + winner;
} else {
status = 'Next player: ' + (xIsNext ? 'X' : 'O');
}
return (
<>
<div className="status">{status}</div>
<div className="board-row">
<Square value={squares[0]} onSquareClick={() => handleClick(0)} />
<Square value={squares[1]} onSquareClick={() => handleClick(1)} />
<Square value={squares[2]} onSquareClick={() => handleClick(2)} />
</div>
<div className="board-row">
<Square value={squares[3]} onSquareClick={() => handleClick(3)} />
<Square value={squares[4]} onSquareClick={() => handleClick(4)} />
<Square value={squares[5]} onSquareClick={() => handleClick(5)} />
</div>
<div className="board-row">
<Square value={squares[6]} onSquareClick={() => handleClick(6)} />
<Square value={squares[7]} onSquareClick={() => handleClick(7)} />
<Square value={squares[8]} onSquareClick={() => handleClick(8)} />
</div>
</>
);
}
export default function Game() {
const [history, setHistory] = useState([Array(9).fill(null)]);
const [currentMove, setCurrentMove] = useState(0);
const xIsNext = currentMove % 2 === 0;
const currentSquares = history[currentMove];
function handlePlay(nextSquares) {
const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
setHistory(nextHistory);
setCurrentMove(nextHistory.length - 1);
}
function jumpTo(nextMove) {
setCurrentMove(nextMove);
}
const moves = history.map((squares, move) => {
let description;
if (move > 0) {
description = 'Go to move #' + move;
} else {
description = 'Go to game start';
}
return (
<li key={move}>
<button onClick={() => jumpTo(move)}>{description}</button>
</li>
);
});
return (
<div className="game">
<div className="game-board">
<Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
</div>
<div className="game-info">
<ol>{moves}</ol>
</div>
</div>
);
}
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
```
Show more
We’d also like to highlight [Thinking in React](https://react.dev/learn/thinking-in-react)—that’s the tutorial that made React “click” for many of us. **We’ve updated both of these classic tutorials to use function components and Hooks,** so they’re as good as new.
### Note
The example above is a *sandbox*. We’ve added a lot of sandboxes—over 600!—everywhere throughout the site. You can edit any sandbox, or press “Fork” in the upper right corner to open it in a separate tab. Sandboxes let you quickly play with the React APIs, explore your ideas, and check your understanding.
## Learn React step by step[Link for Learn React step by step]()
We’d like everyone in the world to have an equal opportunity to learn React for free on their own.
This is why the Learn section is organized like a self-paced course split into chapters. The first two chapters describe the fundamentals of React. If you’re new to React, or want to refresh it in your memory, start here:
- [**Describing the UI**](https://react.dev/learn/describing-the-ui) teaches how to display information with components.
- [**Adding Interactivity**](https://react.dev/learn/adding-interactivity) teaches how to update the screen in response to user input.
The next two chapters are more advanced, and will give you a deeper insight into the trickier parts:
- [**Managing State**](https://react.dev/learn/managing-state) teaches how to organize your logic as your app grows in complexity.
- [**Escape Hatches**](https://react.dev/learn/escape-hatches) teaches how you can “step outside” React, and when it makes most sense to do so.
Every chapter consists of several related pages. Most of these pages teach a specific skill or a technique—for example, [Writing Markup with JSX](https://react.dev/learn/writing-markup-with-jsx), [Updating Objects in State](https://react.dev/learn/updating-objects-in-state), or [Sharing State Between Components](https://react.dev/learn/sharing-state-between-components). Some of the pages focus on explaining an idea—like [Render and Commit](https://react.dev/learn/render-and-commit), or [State as a Snapshot](https://react.dev/learn/state-as-a-snapshot). And there are a few, like [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect), that share our suggestions based on what we’ve learned over these years.
You don’t have to read these chapters as a sequence. Who has the time for this?! But you could. Pages in the Learn section only rely on concepts introduced by the earlier pages. If you want to read it like a book, go for it!
### Check your understanding with challenges[Link for Check your understanding with challenges]()
Most pages in the Learn section end with a few challenges to check your understanding. For example, here are a few challenges from the page about [Conditional Rendering](https://react.dev/learn/conditional-rendering).
You don’t have to solve them right now! Unless you *really* want to.
1\. Show an icon for incomplete items with `? :` 2. Show the item importance with `&&`
#### Challenge 1 of 2: Show an icon for incomplete items with `? :`[Link for this heading]()
Use the conditional operator (`cond ? a : b`) to render a ❌ if `isPacked` isn’t `true`.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked && '✅'}
</li>
);
}
export default function PackingList() {
return (
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item
isPacked={true}
name="Space suit"
/>
<Item
isPacked={true}
name="Helmet with a golden leaf"
/>
<Item
isPacked={false}
name="Photo of Tam"
/>
</ul>
</section>
);
}
```
Show more
Show solutionNext Challenge
Notice the “Show solution” button in the left bottom corner. It’s handy if you want to check yourself!
### Build an intuition with diagrams and illustrations[Link for Build an intuition with diagrams and illustrations]()
When we couldn’t figure out how to explain something with code and words alone, we’ve added diagrams that help provide some intuition. For example, here is one of the diagrams from [Preserving and Resetting State](https://react.dev/learn/preserving-and-resetting-state):
![Diagram with three sections, with an arrow transitioning each section in between. The first section contains a React component labeled 'div' with a single child labeled 'section', which has a single child labeled 'Counter' containing a state bubble labeled 'count' with value 3. The middle section has the same 'div' parent, but the child components have now been deleted, indicated by a yellow 'proof' image. The third section has the same 'div' parent again, now with a new child labeled 'div', highlighted in yellow, also with a new child labeled 'Counter' containing a state bubble labeled 'count' with value 0, all highlighted in yellow.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_diff_same_pt1.dark.png&w=1920&q=75)
![Diagram with three sections, with an arrow transitioning each section in between. The first section contains a React component labeled 'div' with a single child labeled 'section', which has a single child labeled 'Counter' containing a state bubble labeled 'count' with value 3. The middle section has the same 'div' parent, but the child components have now been deleted, indicated by a yellow 'proof' image. The third section has the same 'div' parent again, now with a new child labeled 'div', highlighted in yellow, also with a new child labeled 'Counter' containing a state bubble labeled 'count' with value 0, all highlighted in yellow.](/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_diff_same_pt1.png&w=1920&q=75)
When `section` changes to `div`, the `section` is deleted and the new `div` is added
You’ll also see some illustrations throughout the docs—here’s one of the [browser painting the screen](https://react.dev/learn/render-and-commit):
![A browser painting 'still life with card element'.](/images/docs/illustrations/i_browser-paint.png)
Illustrated by [Rachel Lee Nabors](https://nearestnabors.com/)
We’ve confirmed with the browser vendors that this depiction is 100% scientifically accurate.
## A new, detailed API Reference[Link for A new, detailed API Reference]()
In the [API Reference](https://react.dev/reference/react), every React API now has a dedicated page. This includes all kinds of APIs:
- Built-in Hooks like [`useState`](https://react.dev/reference/react/useState).
- Built-in components like [`<Suspense>`](https://react.dev/reference/react/Suspense).
- Built-in browser components like [`<input>`](https://react.dev/reference/react-dom/components/input).
- Framework-oriented APIs like [`renderToPipeableStream`](https://react.dev/reference/react-dom/server/renderToReadableStream).
- Other React APIs like [`memo`](https://react.dev/reference/react/memo).
You’ll notice that every API page is split into at least two segments: *Reference* and *Usage*.
[Reference](https://react.dev/reference/react/useState) describes the formal API signature by listing its arguments and return values. It’s concise, but it can feel a bit abstract if you’re not familiar with that API. It describes what an API does, but not how to use it.
[Usage](https://react.dev/reference/react/useState) shows why and how you would use this API in practice, like a colleague or a friend might explain. It shows the **canonical scenarios for how each API was meant to be used by the React team.** We’ve added color-coded snippets, examples of using different APIs together, and recipes that you can copy and paste from:
#### Basic useState examples[Link for Basic useState examples]()
1\. Counter (number) 2. Text field (string) 3. Checkbox (boolean) 4. Form (two variables)
#### Example 1 of 4: Counter (number)[Link for this heading]()
In this example, the `count` state variable holds a number. Clicking the button increments it.
App.js
App.js
Reset[Fork](https://codesandbox.io/api/v1/sandboxes/define?undefined&environment=create-react-app "Open in CodeSandbox")
```
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
You pressed me {count} times
</button>
);
}
```
Next Example
Some API pages also include [Troubleshooting](https://react.dev/reference/react/useEffect) (for common problems) and [Alternatives](https://react.dev/reference/react-dom/findDOMNode) (for deprecated APIs).
We hope that this approach will make the API reference useful not only as a way to look up an argument, but as a way to see all the different things you can do with any given API—and how it connects to the other ones.
## What’s next?[Link for What’s next?]()
That’s a wrap for our little tour! Have a look around the new website, see what you like or don’t like, and keep the feedback coming in our [issue tracker](https://github.com/reactjs/react.dev/issues).
We acknowledge this project has taken a long time to ship. We wanted to maintain a high quality bar that the React community deserves. While writing these docs and creating all of the examples, we found mistakes in some of our own explanations, bugs in React, and even gaps in the React design that we are now working to address. We hope that the new documentation will help us hold React itself to a higher bar in the future.
We’ve heard many of your requests to expand the content and functionality of the website, for example:
- Providing a TypeScript version for all examples;
- Creating the updated performance, testing, and accessibility guides;
- Documenting React Server Components independently from the frameworks that support them;
- Working with our international community to get the new docs translated;
- Adding missing features to the new website (for example, RSS for this blog).
Now that [react.dev](https://react.dev/) is out, we will be able to shift our focus from “catching up” with the third-party React educational resources to adding new information and further improving our new website.
We think there’s never been a better time to learn React.
## Who worked on this?[Link for Who worked on this?]()
On the React team, [Rachel Nabors](https://twitter.com/rachelnabors/) led the project (and provided the illustrations), and [Dan Abramov](https://twitter.com/dan_abramov) designed the curriculum. They co-authored most of the content together as well.
Of course, no project this large happens in isolation. We have a lot of people to thank!
[Sylwia Vargas](https://twitter.com/SylwiaVargas) overhauled our examples to go beyond “foo/bar/baz” and kittens, and feature scientists, artists and cities from around the world. [Maggie Appleton](https://twitter.com/Mappletons) turned our doodles into a clear diagram system.
Thanks to [David McCabe](https://twitter.com/mcc_abe), [Sophie Alpert](https://twitter.com/sophiebits), [Rick Hanlon](https://twitter.com/rickhanlonii), [Andrew Clark](https://twitter.com/acdlite), and [Matt Carroll](https://twitter.com/mattcarrollcode) for additional writing contributions. We’d also like to thank [Natalia Tepluhina](https://twitter.com/n_tepluhina) and [Sebastian Markbåge](https://twitter.com/sebmarkbage) for their ideas and feedback.
Thanks to [Dan Lebowitz](https://twitter.com/lebo) for the site design and [Razvan Gradinar](https://dribbble.com/GradinarRazvan) for the sandbox design.
On the development front, thanks to [Jared Palmer](https://twitter.com/jaredpalmer) for prototype development. Thanks to [Dane Grant](https://twitter.com/danecando) and [Dustin Goodman](https://twitter.com/dustinsgoodman) from [ThisDotLabs](https://www.thisdot.co/) for their support on UI development. Thanks to [Ives van Hoorne](https://twitter.com/CompuIves), [Alex Moldovan](https://twitter.com/alexnmoldovan), [Jasper De Moor](https://twitter.com/JasperDeMoor), and [Danilo Woznica](https://twitter.com/danilowoz) from [CodeSandbox](https://codesandbox.io/) for their work with sandbox integration. Thanks to [Rick Hanlon](https://twitter.com/rickhanlonii) for spot development and design work, finessing our colors and finer details. Thanks to [Harish Kumar](https://www.strek.in/) and [Luna Ruan](https://twitter.com/lunaruan) for adding new features to the site and helping maintain it.
Huge thanks to the folks who volunteered their time to participate in the alpha and beta testing program. Your enthusiasm and invaluable feedback helped us shape these docs. A special shout out to our beta tester, [Debbie O’Brien](https://twitter.com/debs_obrien), who gave a talk about her experience using the React docs at React Conf 2021.
Finally, thanks to the React community for being the inspiration behind this effort. You are the reason we do this, and we hope that the new docs will help you use React to build any user interface that you want.
[PreviousReact Labs: What We've Been Working On – March 2023](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023)
[NextReact Labs: What We've Been Working On – June 2022](https://react.dev/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022) |
https://react.dev/blog/2021/12/17/react-conf-2021-recap | [Blog](https://react.dev/blog)
# React Conf 2021 Recap[Link for this heading]()
December 17, 2021 by [Jesslyn Tannady](https://twitter.com/jtannady) and [Rick Hanlon](https://twitter.com/rickhanlonii)
* * *
Last week we hosted our 6th React Conf. In previous years, we’ve used the React Conf stage to deliver industry changing announcements such as [*React Native*](https://engineering.fb.com/2015/03/26/android/react-native-bringing-modern-web-techniques-to-mobile/) and [*React Hooks*](https://reactjs.org/docs/hooks-intro.html). This year, we shared our multi-platform vision for React, starting with the release of React 18 and gradual adoption of concurrent features.
* * *
This was the first time React Conf was hosted online, and it was streamed for free, translated to 8 different languages. Participants from all over the world joined our conference Discord and the replay event for accessibility in all timezones. Over 50,000 people registered, with over 60,000 views of 19 talks, and 5,000 participants in Discord across both events.
All the talks are [available to stream online](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa).
Here’s a summary of what was shared on stage:
## React 18 and concurrent features[Link for React 18 and concurrent features]()
In the keynote, we shared our vision for the future of React starting with React 18.
React 18 adds the long-awaited concurrent renderer and updates to Suspense without any major breaking changes. Apps can upgrade to React 18 and begin gradually adopting concurrent features with the amount of effort on par with any other major release.
**This means there is no concurrent mode, only concurrent features.**
In the keynote, we also shared our vision for Suspense, Server Components, new React working groups, and our long-term many-platform vision for React Native.
Watch the full keynote from [Andrew Clark](https://twitter.com/acdlite), [Juan Tejada](https://twitter.com/_jstejada), [Lauren Tan](https://twitter.com/potetotes), and [Rick Hanlon](https://twitter.com/rickhanlonii) here:
## React 18 for Application Developers[Link for React 18 for Application Developers]()
In the keynote, we also announced that the React 18 RC is available to try now. Pending further feedback, this is the exact version of React that we will publish to stable early next year.
To try the React 18 RC, upgrade your dependencies:
```
npm install react@rc react-dom@rc
```
and switch to the new `createRoot` API:
```
// before
const container = document.getElementById('root');
ReactDOM.render(<App />, container);
// after
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App/>);
```
For a demo of upgrading to React 18, see [Shruti Kapoor](https://twitter.com/shrutikapoor08)’s talk here:
## Streaming Server Rendering with Suspense[Link for Streaming Server Rendering with Suspense]()
React 18 also includes improvements to server-side rendering performance using Suspense.
Streaming server rendering lets you generate HTML from React components on the server, and stream that HTML to your users. In React 18, you can use `Suspense` to break down your app into smaller independent units which can be streamed independently of each other without blocking the rest of the app. This means users will see your content sooner and be able to start interacting with it much faster.
For a deep dive, see [Shaundai Person](https://twitter.com/shaundai)’s talk here:
## The first React working group[Link for The first React working group]()
For React 18, we created our first Working Group to collaborate with a panel of experts, developers, library maintainers, and educators. Together we worked to create our gradual adoption strategy and refine new APIs such as `useId`, `useSyncExternalStore`, and `useInsertionEffect`.
For an overview of this work, see [Aakansha’ Doshi](https://twitter.com/aakansha1216)’s talk:
## React Developer Tooling[Link for React Developer Tooling]()
To support the new features in this release, we also announced the newly formed React DevTools team and a new Timeline Profiler to help developers debug their React apps.
For more information and a demo of new DevTools features, see [Brian Vaughn](https://twitter.com/brian_d_vaughn)’s talk:
## React without memo[Link for React without memo]()
Looking further into the future, [Xuan Huang (黄玄)](https://twitter.com/Huxpro) shared an update from our React Labs research into an auto-memoizing compiler. Check out this talk for more information and a demo of the compiler prototype:
## React docs keynote[Link for React docs keynote]()
[Rachel Nabors](https://twitter.com/rachelnabors) kicked off a section of talks about learning and designing with React with a keynote about our investment in React’s new docs ([now shipped as react.dev](https://react.dev/blog/2023/03/16/introducing-react-dev)):
## And more…[Link for And more…]()
**We also heard talks on learning and designing with React:**
- Debbie O’Brien: [Things I learnt from the new React docs](https://youtu.be/-7odLW_hG7s).
- Sarah Rainsberger: [Learning in the Browser](https://youtu.be/5X-WEQflCL0).
- Linton Ye: [The ROI of Designing with React](https://youtu.be/7cPWmID5XAk).
- Delba de Oliveira: [Interactive playgrounds with React](https://youtu.be/zL8cz2W0z34).
**Talks from the Relay, React Native, and PyTorch teams:**
- Robert Balicki: [Re-introducing Relay](https://youtu.be/lhVGdErZuN4).
- Eric Rozell and Steven Moyes: [React Native Desktop](https://youtu.be/9L4FFrvwJwY).
- Roman Rädle: [On-device Machine Learning for React Native](https://youtu.be/NLj73vrc2I8)
**And talks from the community on accessibility, tooling, and Server Components:**
- Daishi Kato: [React 18 for External Store Libraries](https://youtu.be/oPfSC5bQPR8).
- Diego Haz: [Building Accessible Components in React 18](https://youtu.be/dcm8fjBfro8).
- Tafu Nakazaki: [Accessible Japanese Form Components with React](https://youtu.be/S4a0QlsH0pU).
- Lyle Troxell: [UI tools for artists](https://youtu.be/b3l4WxipFsE).
- Helen Lin: [Hydrogen + React 18](https://youtu.be/HS6vIYkSNks).
## Thank you[Link for Thank you]()
This was our first year planning a conference ourselves, and we have a lot of people to thank.
First, thanks to all of our speakers [Aakansha Doshi](https://twitter.com/aakansha1216), [Andrew Clark](https://twitter.com/acdlite), [Brian Vaughn](https://twitter.com/brian_d_vaughn), [Daishi Kato](https://twitter.com/dai_shi), [Debbie O’Brien](https://twitter.com/debs_obrien), [Delba de Oliveira](https://twitter.com/delba_oliveira), [Diego Haz](https://twitter.com/diegohaz), [Eric Rozell](https://twitter.com/EricRozell), [Helen Lin](https://twitter.com/wizardlyhel), [Juan Tejada](https://twitter.com/_jstejada), [Lauren Tan](https://twitter.com/potetotes), [Linton Ye](https://twitter.com/lintonye), [Lyle Troxell](https://twitter.com/lyle), [Rachel Nabors](https://twitter.com/rachelnabors), [Rick Hanlon](https://twitter.com/rickhanlonii), [Robert Balicki](https://twitter.com/StatisticsFTW), [Roman Rädle](https://twitter.com/raedle), [Sarah Rainsberger](https://twitter.com/sarah11918), [Shaundai Person](https://twitter.com/shaundai), [Shruti Kapoor](https://twitter.com/shrutikapoor08), [Steven Moyes](https://twitter.com/moyessa), [Tafu Nakazaki](https://twitter.com/hawaiiman0), and [Xuan Huang (黄玄)](https://twitter.com/Huxpro).
Thanks to everyone who helped provide feedback on talks including [Andrew Clark](https://twitter.com/acdlite), [Dan Abramov](https://twitter.com/dan_abramov), [Dave McCabe](https://twitter.com/mcc_abe), [Eli White](https://twitter.com/Eli_White), [Joe Savona](https://twitter.com/en_JS), [Lauren Tan](https://twitter.com/potetotes), [Rachel Nabors](https://twitter.com/rachelnabors), and [Tim Yung](https://twitter.com/yungsters).
Thanks to [Lauren Tan](https://twitter.com/potetotes) for setting up the conference Discord and serving as our Discord admin.
Thanks to [Seth Webster](https://twitter.com/sethwebster) for feedback on overall direction and making sure we were focused on diversity and inclusion.
Thanks to [Rachel Nabors](https://twitter.com/rachelnabors) for spearheading our moderation effort, and [Aisha Blake](https://twitter.com/AishaBlake) for creating our moderation guide, leading our moderation team, training the translators and moderators, and helping to moderate both events.
Thanks to our moderators [Jesslyn Tannady](https://twitter.com/jtannady), [Suzie Grange](https://twitter.com/missuze), [Becca Bailey](https://twitter.com/beccaliz), [Luna Wei](https://twitter.com/lunaleaps), [Joe Previte](https://twitter.com/jsjoeio), [Nicola Corti](https://twitter.com/Cortinico), [Gijs Weterings](https://twitter.com/gweterings), [Claudio Procida](https://twitter.com/claudiopro), Julia Neumann, Mengdi Chen, Jean Zhang, Ricky Li, and [Xuan Huang (黄玄)](https://twitter.com/Huxpro).
Thanks to [Manjula Dube](https://twitter.com/manjula_dube), [Sahil Mhapsekar](https://twitter.com/apheri0), and Vihang Patel from [React India](https://www.reactindia.io/), and [Jasmine Xie](https://twitter.com/jasmine_xby), [QiChang Li](https://twitter.com/QCL15), and [YanLun Li](https://twitter.com/anneincoding) from [React China](https://twitter.com/ReactChina) for helping moderate our replay event and keep it engaging for the community.
Thanks to Vercel for publishing their [Virtual Event Starter Kit](https://vercel.com/virtual-event-starter-kit), which the conference website was built on, and to [Lee Robinson](https://twitter.com/leeerob) and [Delba de Oliveira](https://twitter.com/delba_oliveira) for sharing their experience running Next.js Conf.
Thanks to [Leah Silber](https://twitter.com/wifelette) for sharing her experience running conferences, learnings from running [RustConf](https://rustconf.com/), and for her book [Event Driven](https://leanpub.com/eventdriven/) and the advice it contains for running conferences.
Thanks to [Kevin Lewis](https://twitter.com/_phzn) and [Rachel Nabors](https://twitter.com/rachelnabors) for sharing their experience running Women of React Conf.
Thanks to [Aakansha Doshi](https://twitter.com/aakansha1216), [Laurie Barth](https://twitter.com/laurieontech), [Michael Chan](https://twitter.com/chantastic), and [Shaundai Person](https://twitter.com/shaundai) for their advice and ideas throughout planning.
Thanks to [Dan Lebowitz](https://twitter.com/lebo) for help designing and building the conference website and tickets.
Thanks to Laura Podolak Waddell, Desmond Osei-Acheampong, Mark Rossi, Josh Toberman and others on the Facebook Video Productions team for recording the videos for the Keynote and Meta employee talks.
Thanks to our partner HitPlay for helping to organize the conference, editing all the videos in the stream, translating all the talks, and moderating the Discord in multiple languages.
Finally, thanks to all of our participants for making this a great React Conf!
[PreviousHow to Upgrade to React 18](https://react.dev/blog/2022/03/08/react-18-upgrade-guide)
[NextThe Plan for React 18](https://react.dev/blog/2021/06/08/the-plan-for-react-18) |
https://react.dev/reference/rsc/directives | [API Reference](https://react.dev/reference/react)
# Directives[Link for this heading]()
### React Server Components
Directives are for use in [React Server Components](https://react.dev/learn/start-a-new-react-project).
Directives provide instructions to [bundlers compatible with React Server Components](https://react.dev/learn/start-a-new-react-project).
* * *
## Source code directives[Link for Source code directives]()
- [`'use client'`](https://react.dev/reference/rsc/use-client) lets you mark what code runs on the client.
- [`'use server'`](https://react.dev/reference/rsc/use-server) marks server-side functions that can be called from client-side code.
[PreviousServer Functions](https://react.dev/reference/rsc/server-functions)
[Next'use client'](https://react.dev/reference/rsc/use-client) |
https://react.dev/reference/react/legacy | [API Reference](https://react.dev/reference/react)
# Legacy React APIs[Link for this heading]()
These APIs are exported from the `react` package, but they are not recommended for use in newly written code. See the linked individual API pages for the suggested alternatives.
* * *
## Legacy APIs[Link for Legacy APIs]()
- [`Children`](https://react.dev/reference/react/Children) lets you manipulate and transform the JSX received as the `children` prop. [See alternatives.](https://react.dev/reference/react/Children)
- [`cloneElement`](https://react.dev/reference/react/cloneElement) lets you create a React element using another element as a starting point. [See alternatives.](https://react.dev/reference/react/cloneElement)
- [`Component`](https://react.dev/reference/react/Component) lets you define a React component as a JavaScript class. [See alternatives.](https://react.dev/reference/react/Component)
- [`createElement`](https://react.dev/reference/react/createElement) lets you create a React element. Typically, you’ll use JSX instead.
- [`createRef`](https://react.dev/reference/react/createRef) creates a ref object which can contain arbitrary value. [See alternatives.](https://react.dev/reference/react/createRef)
- [`forwardRef`](https://react.dev/reference/react/forwardRef) lets your component expose a DOM node to parent component with a [ref.](https://react.dev/learn/manipulating-the-dom-with-refs)
- [`isValidElement`](https://react.dev/reference/react/isValidElement) checks whether a value is a React element. Typically used with [`cloneElement`.](https://react.dev/reference/react/cloneElement)
- [`PureComponent`](https://react.dev/reference/react/PureComponent) is similar to [`Component`,](https://react.dev/reference/react/Component) but it skip re-renders with same props. [See alternatives.](https://react.dev/reference/react/PureComponent)
* * *
## Removed APIs[Link for Removed APIs]()
These APIs were removed in React 19:
- [`createFactory`](https://18.react.dev/reference/react/createFactory): use JSX instead.
- Class Components: [`static contextTypes`](https://18.react.dev//reference/react/Component): use [`static contextType`]() instead.
- Class Components: [`static childContextTypes`](https://18.react.dev//reference/react/Component): use [`static contextType`]() instead.
- Class Components: [`static getChildContext`](https://18.react.dev//reference/react/Component): use [`Context.Provider`](https://react.dev/reference/react/createContext) instead.
- Class Components: [`static propTypes`](https://18.react.dev//reference/react/Component): use a type system like [TypeScript](https://www.typescriptlang.org/) instead.
- Class Components: [`this.refs`](https://18.react.dev//reference/react/Component): use [`createRef`](https://react.dev/reference/react/createRef) instead.
[NextChildren](https://react.dev/reference/react/Children) |