1,291 captures
25 Oct 2018 - 28 Feb 2026
Aug SEP Oct
02
2020 2021 2022
success
fail

About this capture

COLLECTED BY

Collection: Save Page Now

TIMESTAMPS

The Wayback Machine - http://web.archive.org/web/20210902194706/https://reactjs.org/docs/hooks-intro.html
 

We want to hear from you!Take our 2021 Community Survey!
React
v17.0.2 LanguagesGitHub

Introducing Hooks


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 well learn about, but this example is just a teaser. Dont worry if it doesnt make sense yet!

You can start learning Hooks on the next page. On this page, well continue by explaining why were 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, dont forget to update all packages, including React DOM. React Native supports Hooks since the 0.59 release of React Native.

Video Introduction 


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:


No Breaking Changes 


Before we continue, note that Hooks are:


Completely opt-in. You can try Hooks in a few components without rewriting any existing code. But you dont have to learn or use Hooks right now if you dont want to.

100% backwards-compatible. Hooks dont contain any breaking changes.

Available now. Hooks are now available with the release of v16.8.0.


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 dont 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 were adding Hooks, and how were going to start using them without rewriting our applications.

Motivation 


Hooks solve a wide variety of seemingly unconnected problems in React that weve encountered over five years of writing and maintaining tens of thousands of components. Whether youre learning React, use it daily, or even prefer a different library with a similar component model, you might recognize some of these problems.

Its hard to reuse stateful logic between components 


React doesnt offer a way to attach reusable behavior to a component (for example, connecting it to a store). If youve 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.

Well discuss this more in Building Your Own Hooks.

Complex components become hard to understand 


Weve 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 its not possible to break these components into smaller ones because the stateful logic is all over the place. Its 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 components local state with a reducer to make it more predictable.

Well discuss this more in Using the Effect Hook.

Classes confuse both people and machines 


In addition to making code reuse and code organization more difficult, weve 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 unstable syntax proposals, 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 its not limited to templates. Recently, weve been experimenting with component folding using Prepack, and weve 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 todays tools, too. For example, classes dont 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 Reacts 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 dont require you to learn complex functional or reactive programming techniques.


Examples

Hooks at a Glance is a good place to start learning Hooks.

Gradual Adoption Strategy 



TLDR: There are no plans to remove classes from React.


We know that React developers are focused on shipping products and dont have time to look into every new API thats 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 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, its 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.

Frequently Asked Questions 


Weve prepared a Hooks FAQ page that answers the most common questions about Hooks.

Next Steps 


By the end of this page, you should have a rough idea of what problems Hooks are solving, but many details are probably unclear. Dont worry! Lets now go to the next page where we start learning about Hooks by example.
Is this page useful?Edit this page



Installation

Getting Started
Add React to a Website
Create a New React App
CDN Links
Release Channels

Main Concepts

1. Hello World
2. Introducing JSX
3. Rendering Elements
4. Components and Props
5. State and Lifecycle
6. Handling Events
7. Conditional Rendering
8. Lists and Keys
9. Forms
10. Lifting State Up
11. Composition vs Inheritance
12. Thinking In React

Advanced Guides

Accessibility
Code-Splitting
Context
Error Boundaries
Forwarding Refs
Fragments
Higher-Order Components
Integrating with Other Libraries
JSX In Depth
Optimizing Performance
Portals
Profiler
React Without ES6
React Without JSX
Reconciliation
Refs and the DOM
Render Props
Static Type Checking
Strict Mode
Typechecking With PropTypes
Uncontrolled Components
Web Components

API Reference

React
React.Component
ReactDOM
ReactDOMServer
DOM Elements
SyntheticEvent
Test Utilities
Test Renderer
JS Environment Requirements
Glossary

Hooks

1. Introducing Hooks
2. Hooks at a Glance
3. Using the State Hook
4. Using the Effect Hook
5. Rules of Hooks
6. Building Your Own Hooks
7. Hooks API Reference
8. Hooks FAQ

Testing

Testing Overview
Testing Recipes
Testing Environments

Contributing

How to Contribute
Codebase Overview
Implementation Notes
Design Principles

FAQ

AJAX and APIs
Babel, JSX, and Build Steps
Passing Functions to Components
Component State
Styling and CSS
File Structure
Versioning Policy
Virtual DOM and Internals
Next article
Hooks at a Glance

Docs
InstallationMain ConceptsAdvanced GuidesAPI ReferenceHooksTestingContributingFAQ
Channels
GitHubStack OverflowDiscussion ForumsReactiflux ChatDEV CommunityFacebookTwitter
Community
Code of ConductCommunity Resources
More
TutorialBlogAcknowledgementsReact NativePrivacyTerms
Facebook Open Source
Copyright © 2021 Facebook Inc.