This is one stop global knowledge base where you can learn about all the products, solutions and support features.
Importing
import ReactTestUtils from 'react-dom/test-utils'; // ES6
var ReactTestUtils = require('react-dom/test-utils'); // ES5 with npm
ReactTestUtils
makes it easy to test React components in the testing framework of your choice. At Facebook we use Jest for painless JavaScript testing. Learn how to get started with Jest through the Jest website’s React Tutorial.
Note:
We recommend using React Testing Library which is designed to enable and encourage writing tests that use your components as the end users do.
For React versions <= 16, the Enzyme library makes it easy to assert, manipulate, and traverse your React Components’ output.
act()
mockComponent()
isElement()
isElementOfType()
isDOMComponent()
isCompositeComponent()
isCompositeComponentWithType()
findAllInRenderedTree()
scryRenderedDOMComponentsWithClass()
findRenderedDOMComponentWithClass()
scryRenderedDOMComponentsWithTag()
findRenderedDOMComponentWithTag()
scryRenderedComponentsWithType()
findRenderedComponentWithType()
renderIntoDocument()
Simulate
act()
To prepare a component for assertions, wrap the code rendering it and performing updates inside an
act()
call. This makes your test run closer to how React works in the browser.
Note
If you use
react-test-renderer
, it also provides anact
export that behaves the same way.
For example, let’s say we have this
Counter
component:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: 0};
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
handleClick() {
this.setState(state => ({
count: state.count + 1,
}));
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.handleClick}>
Click me
</button>
</div>
);
}
}
Here is how we can test it:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { act } from 'react-dom/test-utils';import Counter from './Counter';
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('can render and update a counter', () => {
// Test first render and componentDidMount
act(() => { ReactDOM.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');
// Test second render and componentDidUpdate
act(() => { button.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(label.textContent).toBe('You clicked 1 times');
expect(document.title).toBe('You clicked 1 times');
});
document
. You can use a library like React Testing Library to reduce the boilerplate code.
recipes
document contains more details on how
act()
behaves, with examples and usage.
mockComponent()
mockComponent(
componentClass,
[mockTagName]
)
Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple
<div>
(or other tag if
mockTagName
is provided) containing any provided children.
Note:
mockComponent()
is a legacy API. We recommend usingjest.mock()
instead.
isElement()
isElement(element)
Returns
true
if
element
is any React element.
isElementOfType()
isElementOfType(
element,
componentClass
)
Returns
true
if
element
is a React element whose type is of a React
componentClass
.
isDOMComponent()
isDOMComponent(instance)
Returns
true
if
instance
is a DOM component (such as a
<div>
or
<span>
).
isCompositeComponent()
isCompositeComponent(instance)
Returns
true
if
instance
is a user-defined component, such as a class or a function.
isCompositeComponentWithType()
isCompositeComponentWithType(
instance,
componentClass
)
Returns
true
if
instance
is a component whose type is of a React
componentClass
.
findAllInRenderedTree()
findAllInRenderedTree(
tree,
test
)
Traverse all components in
tree
and accumulate all components where
test(component)
is
true
. This is not that useful on its own, but it’s used as a primitive for other test utils.
scryRenderedDOMComponentsWithClass()
scryRenderedDOMComponentsWithClass(
tree,
className
)
Finds all DOM elements of components in the rendered tree that are DOM components with the class name matching
className
.
findRenderedDOMComponentWithClass()
findRenderedDOMComponentWithClass(
tree,
className
)
Like
scryRenderedDOMComponentsWithClass()
but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
scryRenderedDOMComponentsWithTag()
scryRenderedDOMComponentsWithTag(
tree,
tagName
)
Finds all DOM elements of components in the rendered tree that are DOM components with the tag name matching
tagName
.
findRenderedDOMComponentWithTag()
findRenderedDOMComponentWithTag(
tree,
tagName
)
Like
scryRenderedDOMComponentsWithTag()
but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
scryRenderedComponentsWithType()
scryRenderedComponentsWithType(
tree,
componentClass
)
Finds all instances of components with type equal to
componentClass
.
findRenderedComponentWithType()
findRenderedComponentWithType(
tree,
componentClass
)
Same as
scryRenderedComponentsWithType()
but expects there to be one result and returns that one result, or throws exception if there is any other number of matches besides one.
renderIntoDocument()
renderIntoDocument(element)
Render a React element into a detached DOM node in the document. This function requires a DOM. It is effectively equivalent to:
const domContainer = document.createElement('div');
ReactDOM.createRoot(domContainer).render(element);
Note:
You will need to have
window
,window.document
andwindow.document.createElement
globally available before you importReact
. Otherwise React will think it can’t access the DOM and methods likesetState
won’t work.
Simulate
Simulate.{eventName}(
element,
[eventData]
)
Simulate an event dispatch on a DOM node with optional
eventData
event data.
Simulate
has a method for every event that React understands.
Clicking an element
// <button ref={(node) => this.button = node}>...</button>
const node = this.button;
ReactTestUtils.Simulate.click(node);
Changing the value of an input field and then pressing ENTER.
// <input ref={(node) => this.textInput = node} />
const node = this.textInput;
node.value = 'giraffe';
ReactTestUtils.Simulate.change(node);
ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
Note
You will have to provide any event property that you’re using in your component (e.g. keyCode, which, etc…) as React is not creating any of these for you.
Importing
import TestRenderer from 'react-test-renderer'; // ES6
const TestRenderer = require('react-test-renderer'); // ES5 with npm
This package provides a React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.
Essentially, this package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a React DOM or React Native component without using a browser or jsdom.
Example:
import TestRenderer from 'react-test-renderer';
function Link(props) {
return <a href={props.page}>{props.children}</a>;
}
const testRenderer = TestRenderer.create(
<Link page="https://www.facebook.com/">Facebook</Link>
);
console.log(testRenderer.toJSON());
// { type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ] }
You can use Jest’s snapshot testing feature to automatically save a copy of the JSON tree to a file and check in your tests that it hasn’t changed: Learn more about it.
You can also traverse the output to find specific nodes and make assertions about them.
import TestRenderer from 'react-test-renderer';
function MyComponent() {
return (
<div>
<SubComponent foo="bar" />
<p className="my">Hello</p>
</div>
)
}
function SubComponent() {
return (
<p className="sub">Sub</p>
);
}
const testRenderer = TestRenderer.create(<MyComponent />);
const testInstance = testRenderer.root;
expect(testInstance.findByType(SubComponent).props.foo).toBe('bar');
expect(testInstance.findByProps({className: "sub"}).children).toEqual(['Sub']);
TestRenderer.create()
TestRenderer.act()
testRenderer.toJSON()
testRenderer.toTree()
testRenderer.update()
testRenderer.unmount()
testRenderer.getInstance()
testRenderer.root
testInstance.find()
testInstance.findByType()
testInstance.findByProps()
testInstance.findAll()
testInstance.findAllByType()
testInstance.findAllByProps()
testInstance.instance
testInstance.type
testInstance.props
testInstance.parent
testInstance.children
TestRenderer.create()
TestRenderer.create(element, options);
Create a
TestRenderer
instance with the passed React element. It doesn’t use the real DOM, but it still fully renders the component tree into memory so you can make assertions about it. Returns a TestRenderer instance.
TestRenderer.act()
TestRenderer.act(callback);
Similar to the
act()
helper from
react-dom/test-utils
,
TestRenderer.act
prepares a component for assertions. Use this version of
act()
to wrap calls to
TestRenderer.create
and
testRenderer.update
.
import {create, act} from 'react-test-renderer';
import App from './app.js'; // The component being tested
// render the component
let root;
act(() => {
root = create(<App value={1}/>)
});
// make assertions on root
expect(root.toJSON()).toMatchSnapshot();
// update with some different props
act(() => {
root.update(<App value={2}/>);
})
// make assertions on root
expect(root.toJSON()).toMatchSnapshot();
testRenderer.toJSON()
testRenderer.toJSON()
Return an object representing the rendered tree. This tree only contains the platform-specific nodes like
<div>
or
<View>
and their props, but doesn’t contain any user-written components. This is handy for snapshot testing.
testRenderer.toTree()
testRenderer.toTree()
Return an object representing the rendered tree. The representation is more detailed than the one provided by
toJSON()
, and includes the user-written components. You probably don’t need this method unless you’re writing your own assertion library on top of the test renderer.
testRenderer.update()
testRenderer.update(element)
Re-render the in-memory tree with a new root element. This simulates a React update at the root. If the new element has the same type and key as the previous element, the tree will be updated; otherwise, it will re-mount a new tree.
testRenderer.unmount()
testRenderer.unmount()
Unmount the in-memory tree, triggering the appropriate lifecycle events.
testRenderer.getInstance()
testRenderer.getInstance()
Return the instance corresponding to the root element, if available. This will not work if the root element is a function component because they don’t have instances.
testRenderer.root
testRenderer.root
Returns the root “test instance” object that is useful for making assertions about specific nodes in the tree. You can use it to find other “test instances” deeper below.
testInstance.find()
testInstance.find(test)
Find a single descendant test instance for which
test(testInstance)
returns
true
. If
test(testInstance)
does not return
true
for exactly one test instance, it will throw an error.
testInstance.findByType()
testInstance.findByType(type)
Find a single descendant test instance with the provided
type
. If there is not exactly one test instance with the provided
type
, it will throw an error.
testInstance.findByProps()
testInstance.findByProps(props)
Find a single descendant test instance with the provided
props
. If there is not exactly one test instance with the provided
props
, it will throw an error.
testInstance.findAll()
testInstance.findAll(test)
Find all descendant test instances for which
test(testInstance)
returns
true
.
testInstance.findAllByType()
testInstance.findAllByType(type)
Find all descendant test instances with the provided
type
.
testInstance.findAllByProps()
testInstance.findAllByProps(props)
Find all descendant test instances with the provided
props
.
testInstance.instance
testInstance.instance
The component instance corresponding to this test instance. It is only available for class components, as function components don’t have instances. It matches the
this
value inside the given component.
testInstance.type
testInstance.type
The component type corresponding to this test instance. For example, a
<Button />
component has a type of
Button
.
testInstance.props
testInstance.props
The props corresponding to this test instance. For example, a
<Button size="small" />
component has
{size: 'small'}
as props.
testInstance.parent
testInstance.parent
The parent test instance of this test instance.
testInstance.children
testInstance.children
The children test instances of this test instance.
You can pass
createNodeMock
function to
TestRenderer.create
as the option, which allows for custom mock refs.
createNodeMock
accepts the current element and should return a mock ref object.
This is useful when you test a component that relies on refs.
import TestRenderer from 'react-test-renderer';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.input = null;
}
componentDidMount() {
this.input.focus();
}
render() {
return <input type="text" ref={el => this.input = el} />
}
}
let focused = false;
TestRenderer.create(
<MyComponent />,
{
createNodeMock: (element) => {
if (element.type === 'input') {
// mock a focus function
return {
focus: () => {
focused = true;
}
};
}
return null;
}
}
);
expect(focused).toBe(true);
React 18 supports all modern browsers (Edge, Firefox, Chrome, Safari, etc).
If you support older browsers and devices such as Internet Explorer which do not provide modern browser features natively or have non-compliant implementations, consider including a global polyfill in your bundled application.
Here is a list of the modern features React 18 uses:
Promise
Symbol
Object.assign
The correct polyfill for these features depend on your environment. For many users, you can configure your Browserlist settings. For others, you may need to import polyfills like
core-js
directly.
A single-page application is an application that loads a single HTML page and all the necessary assets (such as JavaScript and CSS) required for the application to run. Any interactions with the page or subsequent pages do not require a round trip to the server which means the page is not reloaded.
Though you may build a single-page application in React, it is not a requirement. React can also be used for enhancing small parts of existing websites with additional interactivity. Code written in React can coexist peacefully with markup rendered on the server by something like PHP, or with other client-side libraries. In fact, this is exactly how React is being used at Facebook.
These acronyms all refer to the most recent versions of the ECMAScript Language Specification standard, which the JavaScript language is an implementation of. The ES6 version (also known as ES2015) includes many additions to the previous versions such as: arrow functions, classes, template literals,
let
and
const
statements. You can learn more about specific versions here.
A JavaScript compiler takes JavaScript code, transforms it and returns JavaScript code in a different format. The most common use case is to take ES6 syntax and transform it into syntax that older browsers are capable of interpreting. Babel is the compiler most commonly used with React.
Bundlers take JavaScript and CSS code written as separate modules (often hundreds of them), and combine them together into a few files better optimized for the browsers. Some bundlers commonly used in React applications include Webpack and Browserify.
Package managers are tools that allow you to manage dependencies in your project. npm and Yarn are two package managers commonly used in React applications. Both of them are clients for the same npm package registry.
CDN stands for Content Delivery Network. CDNs deliver cached, static content from a network of servers across the globe.
JSX is a syntax extension to JavaScript. It is similar to a template language, but it has full power of JavaScript. JSX gets compiled to
React.createElement()
calls which return plain JavaScript objects called “React elements”. To get a basic introduction to JSX see the docs here and find a more in-depth tutorial on JSX here.
React DOM uses camelCase property naming convention instead of HTML attribute names. For example,
tabindex
becomes
tabIndex
in JSX. The attribute
class
is also written as
className
since
class
is a reserved word in JavaScript:
<h1 className="hello">My name is Clementine!</h1>
React elements are the building blocks of React applications. One might confuse elements with a more widely known concept of “components”. An element describes what you want to see on the screen. React elements are immutable.
const element = <h1>Hello, world</h1>;
Typically, elements are not used directly, but get returned from components.
React components are small, reusable pieces of code that return a React element to be rendered to the page. The simplest version of React component is a plain JavaScript function that returns a React element:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Components can also be ES6 classes:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Components can be broken down into distinct pieces of functionality and used within other components. Components can return other components, arrays, strings and numbers. A good rule of thumb is that if a part of your UI is used several times (Button, Panel, Avatar), or is complex enough on its own (App, FeedStory, Comment), it is a good candidate to be a reusable component. Component names should also always start with a capital letter (
<Wrapper/>
not
<wrapper/>
). See this documentation for more information on rendering components.
props
props
are inputs to a React component. They are data passed down from a parent component to a child component.
Remember that
props
are readonly. They should not be modified in any way:
// Wrong!
props.number = 42;
If you need to modify some value in response to user input or a network response, use
state
instead.
props.children
props.children
is available on every component. It contains the content between the opening and closing tags of a component. For example:
<Welcome>Hello world!</Welcome>
The string
Hello world!
is available in
props.children
in the
Welcome
component:
function Welcome(props) {
return <p>{props.children}</p>;
}
For components defined as classes, use
this.props.children
:
class Welcome extends React.Component {
render() {
return <p>{this.props.children}</p>;
}
}
state
A component needs
state
when some data associated with it changes over time. For example, a
Checkbox
component might need
isChecked
in its state, and a
NewsFeed
component might want to keep track of
fetchedPosts
in its state.
The most important difference between
state
and
props
is that
props
are passed from a parent component, but
state
is managed by the component itself. A component cannot change its
props
, but it can change its
state
.
For each particular piece of changing data, there should be just one component that “owns” it in its state. Don’t try to synchronize states of two different components. Instead, lift it up to their closest shared ancestor, and pass it down as props to both of them.
Lifecycle methods are custom functionality that gets executed during the different phases of a component. There are methods available when the component gets created and inserted into the DOM (mounting), when the component updates, and when the component gets unmounted or removed from the DOM.
React has two different approaches to dealing with form inputs.
An input form element whose value is controlled by React is called a controlled component . When a user enters data into a controlled component a change event handler is triggered and your code decides whether the input is valid (by re-rendering with the updated value). If you do not re-render then the form element will remain unchanged.
An uncontrolled component works like form elements do outside of React. When a user inputs data into a form field (an input box, dropdown, etc) the updated information is reflected without React needing to do anything. However, this also means that you can’t force the field to have a certain value.
In most cases you should use controlled components.
A “key” is a special string attribute you need to include when creating arrays of elements. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside an array to give the elements a stable identity.
Keys only need to be unique among sibling elements in the same array. They don’t need to be unique across the whole application or even a single component.
Don’t pass something like
Math.random()
to keys. It is important that keys have a “stable identity” across re-renders so that React can determine when items are added, removed, or re-ordered. Ideally, keys should correspond to unique and stable identifiers coming from your data, such as
post.id
.
React supports a special attribute that you can attach to any component. The
ref
attribute can be an object created by
React.createRef()
function or a callback function, or a string (in legacy API). When the
ref
attribute is a callback function, the function receives the underlying DOM element or class instance (depending on the type of element) as its argument. This allows you to have direct access to the DOM element or component instance.
Use refs sparingly. If you find yourself often using refs to “make things happen” in your app, consider getting more familiar with top-down data flow.
Handling events with React elements has some syntactic differences:
When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called “reconciliation”.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
This new function
useState
is the first “Hook” we’ll learn about, but this example is just a teaser. Don’t worry if it doesn’t make sense yet!
You can start learning Hooks on the next page. On this page, we’ll continue by explaining why we’re adding Hooks to React and how they can help you write great applications.
Note
React 16.8.0 is the first release to support Hooks. When upgrading, don’t forget to update all packages, including React DOM.
React Native has supported Hooks since the 0.59 release of React Native.
At React Conf 2018, Sophie Alpert and Dan Abramov introduced Hooks, followed by Ryan Florence demonstrating how to refactor an application to use them. Watch the video here:
Before we continue, note that Hooks are:
There are no plans to remove classes from React. You can read more about the gradual adoption strategy for Hooks in the bottom section of this page.
Hooks don’t replace your knowledge of React concepts. Instead, Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful way to combine them.
If you just want to start learning Hooks, feel free to jump directly to the next page! You can also keep reading this page to learn more about why we’re adding Hooks, and how we’re going to start using them without rewriting our applications.
Hooks solve a wide variety of seemingly unconnected problems in React that we’ve encountered over five years of writing and maintaining tens of thousands of components. Whether you’re learning React, use it daily, or even prefer a different library with a similar component model, you might recognize some of these problems.
React doesn’t offer a way to “attach” reusable behavior to a component (for example, connecting it to a store). If you’ve worked with React for a while, you may be familiar with patterns like render props and higher-order components that try to solve this. But these patterns require you to restructure your components when you use them, which can be cumbersome and make code harder to follow. If you look at a typical React application in React DevTools, you will likely find a “wrapper hell” of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions. While we could filter them out in DevTools, this points to a deeper underlying problem: React needs a better primitive for sharing stateful logic.
With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.
We’ll discuss this more in Building Your Own Hooks.
We’ve often had to maintain components that started out simple but grew into an unmanageable mess of stateful logic and side effects. Each lifecycle method often contains a mix of unrelated logic. For example, components might perform some data fetching in
componentDidMount
and
componentDidUpdate
. However, the same
componentDidMount
method might also contain some unrelated logic that sets up event listeners, with cleanup performed in
componentWillUnmount
. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
In many cases it’s not possible to break these components into smaller ones because the stateful logic is all over the place. It’s also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library. However, that often introduces too much abstraction, requires you to jump between different files, and makes reusing components more difficult.
To solve this, Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data) , rather than forcing a split based on lifecycle methods. You may also opt into managing the component’s local state with a reducer to make it more predictable.
We’ll discuss this more in Using the Effect Hook.
In addition to making code reuse and code organization more difficult, we’ve found that classes can be a large barrier to learning React. You have to understand how
this
works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without ES2022 public class fields, the code is very verbose. People can understand props, state, and top-down data flow perfectly well but still struggle with classes. The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers.
Additionally, React has been out for about five years, and we want to make sure it stays relevant in the next five years. As Svelte, Angular, Glimmer, and others show, ahead-of-time compilation of components has a lot of future potential. Especially if it’s not limited to templates. Recently, we’ve been experimenting with component folding using Prepack, and we’ve seen promising early results. However, we found that class components can encourage unintentional patterns that make these optimizations fall back to a slower path. Classes present issues for today’s tools, too. For example, classes don’t minify very well, and they make hot reloading flaky and unreliable. We want to present an API that makes it more likely for code to stay on the optimizable path.
To solve these problems, Hooks let you use more of React’s features without classes. Conceptually, React components have always been closer to functions. Hooks embrace functions, but without sacrificing the practical spirit of React. Hooks provide access to imperative escape hatches and don’t require you to learn complex functional or reactive programming techniques.
Examples
Hooks at a Glance is a good place to start learning Hooks.
TLDR: There are no plans to remove classes from React.
We know that React developers are focused on shipping products and don’t have time to look into every new API that’s being released. Hooks are very new, and it might be better to wait for more examples and tutorials before considering learning or adopting them.
We also understand that the bar for adding a new primitive to React is extremely high. For curious readers, we have prepared a detailed RFC that dives into the motivation with more details, and provides extra perspective on the specific design decisions and related prior art.
Crucially, Hooks work side-by-side with existing code so you can adopt them gradually. There is no rush to migrate to Hooks. We recommend avoiding any “big rewrites”, especially for existing, complex class components. It takes a bit of a mind shift to start “thinking in Hooks”. In our experience, it’s best to practice using Hooks in new and non-critical components first, and ensure that everybody on your team feels comfortable with them. After you give Hooks a try, please feel free to send us feedback, positive or negative.
We intend for Hooks to cover all existing use cases for classes, but we will keep supporting class components for the foreseeable future. At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes.
We’ve prepared a Hooks FAQ page that answers the most common questions about Hooks.
By the end of this page, you should have a rough idea of what problems Hooks are solving, but many details are probably unclear. Don’t worry! Let’s now go to the next page where we start learning about Hooks by example.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
Detailed Explanation
Read the Motivation to learn why we’re introducing Hooks to React.
↑↑↑ Each section ends with a yellow box like this. They link to detailed explanations.
This example renders a counter. When you click the button, it increments the value:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Here,
useState
is a
Hook
(we’ll talk about what this means in a moment). We call it inside a function component to add some local state to it. React will preserve this state between re-renders.
useState
returns a pair: the
current
state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to
this.setState
in a class, except it doesn’t merge the old and new state together. (We’ll show an example comparing
useState
to
this.state
in Using the State Hook.)
The only argument to
useState
is the initial state. In the example above, it is
0
because our counter starts from zero. Note that unlike
this.state
, the state here doesn’t have to be an object — although it can be if you want. The initial state argument is only used during the first render.
You can use the State Hook more than once in a single component:
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}
The array destructuring syntax lets us give different names to the state variables we declared by calling
useState
. These names aren’t a part of the
useState
API. Instead, React assumes that if you call
useState
many times, you do it in the same order during every render. We’ll come back to why this works and when this is useful later.
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. (We don’t recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you’d like.)
React provides a few built-in Hooks like
useState
. You can also create your own Hooks to reuse stateful behavior between different components. We’ll look at the built-in Hooks first.
Detailed Explanation
You can learn more about the State Hook on a dedicated page: Using the State Hook.
You’ve likely performed data fetching, subscriptions, or manually changing the DOM from React components before. We call these operations “side effects” (or “effects” for short) because they can affect other components and can’t be done during rendering.
The Effect Hook,
useEffect
, adds the ability to perform side effects from a function component. It serves the same purpose as
componentDidMount
,
componentDidUpdate
, and
componentWillUnmount
in React classes, but unified into a single API. (We’ll show examples comparing
useEffect
to these methods in Using the Effect Hook.)
For example, this component sets the document title after React updates the DOM:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${count} times`; });
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
When you call
useEffect
, you’re telling React to run your “effect” function after flushing changes to the DOM. Effects are declared inside the component so they have access to its props and state. By default, React runs the effects after every render —
including
the first render. (We’ll talk more about how this compares to class lifecycles in Using the Effect Hook.)
Effects may also optionally specify how to “clean up” after them by returning a function. For example, this component uses an effect to subscribe to a friend’s online status, and cleans up by unsubscribing from it:
import React, { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
useEffect(() => { ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; });
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
In this example, React would unsubscribe from our
ChatAPI
when the component unmounts, as well as before re-running the effect due to a subsequent render. (If you want, there’s a way to tell React to skip re-subscribing if the
props.friend.id
we passed to
ChatAPI
didn’t change.)
Just like with
useState
, you can use more than a single effect in a component:
function FriendStatusWithCounter(props) {
const [count, setCount] = useState(0);
useEffect(() => { document.title = `You clicked ${count} times`;
});
const [isOnline, setIsOnline] = useState(null);
useEffect(() => { ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
// ...
Hooks let you organize side effects in a component by what pieces are related (such as adding and removing a subscription), rather than forcing a split based on lifecycle methods.
Detailed Explanation
You can learn more about
useEffect
on a dedicated page: Using the Effect Hook.
Hooks are JavaScript functions, but they impose two additional rules:
We provide a linter plugin to enforce these rules automatically. We understand these rules might seem limiting or confusing at first, but they are essential to making Hooks work well.
Detailed Explanation
You can learn more about these rules on a dedicated page: Rules of Hooks.
Sometimes, we want to reuse some stateful logic between components. Traditionally, there were two popular solutions to this problem: higher-order components and render props. Custom Hooks let you do this, but without adding more components to your tree.
Earlier on this page, we introduced a
FriendStatus
component that calls the
useState
and
useEffect
Hooks to subscribe to a friend’s online status. Let’s say we also want to reuse this subscription logic in another component.
First, we’ll extract this logic into a custom Hook called
useFriendStatus
:
import React, { useState, useEffect } from 'react';
function useFriendStatus(friendID) { const [isOnline, setIsOnline] = useState(null);
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
useEffect(() => {
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
};
});
return isOnline;
}
It takes
friendID
as an argument, and returns whether our friend is online.
Now we can use it from both components:
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
function FriendListItem(props) {
const isOnline = useFriendStatus(props.friend.id);
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>
);
}
The state of each component is completely independent. Hooks are a way to reuse stateful logic , not state itself. In fact, each call to a Hook has a completely isolated state — so you can even use the same custom Hook twice in one component.
Custom Hooks are more of a convention than a feature. If a function’s name starts with ”
use
” and it calls other Hooks, we say it is a custom Hook. The
useSomething
naming convention is how our linter plugin is able to find bugs in the code using Hooks.
You can write custom Hooks that cover a wide range of use cases like form handling, animation, declarative subscriptions, timers, and probably many more we haven’t considered. We are excited to see what custom Hooks the React community will come up with.
Detailed Explanation
You can learn more about custom Hooks on a dedicated page: Building Your Own Hooks.
There are a few less commonly used built-in Hooks that you might find useful. For example,
useContext
lets you subscribe to React context without introducing nesting:
function Example() {
const locale = useContext(LocaleContext); const theme = useContext(ThemeContext); // ...
}
And
useReducer
lets you manage local state of complex components with a reducer:
function Todos() {
const [todos, dispatch] = useReducer(todosReducer); // ...
Detailed Explanation
You can learn more about all the built-in Hooks on a dedicated page: Hooks API Reference.
Phew, that was fast! If some things didn’t quite make sense or you’d like to learn more in detail, you can read the next pages, starting with the State Hook documentation.
You can also check out the Hooks API reference and the Hooks FAQ.
Finally, don’t miss the introduction page which explains why we’re adding Hooks and how we’ll start using them side by side with classes — without rewriting our apps.