

React v16.8: The One with Hooks
source link: https://www.tuicool.com/articles/hit/zMNNzif
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

With React 16.8,React Hooks are available in a stable release!
What Are Hooks?
Hooks let you use state and other React features without writing a class. You can also build your own Hooks to share reusable stateful logic between components.
If you’ve never heard of Hooks before, you might find these resources interesting:
- Introducing Hooks explains why we’re adding Hooks to React.
- Hooks at a Glance is a fast-paced overview of the built-in Hooks.
- Building Your Own Hooks demonstrates code reuse with custom Hooks.
- Making Sense of React Hooks explores the new possibilities unlocked by Hooks.
- useHooks.com showcases community-maintained Hooks recipes and demos.
You don’t have to learn Hooks right now.Hooks have no breaking changes, and we have no plans to remove classes from React. TheHooks FAQ describes the gradual adoption strategy.
No Big Rewrites
We don’t recommend rewriting your existing applications to use Hooks overnight. Instead, try using Hooks in some of the new components, and let us know what you think. Code using Hooks will workside by side with existing code using classes.
Can I Use Hooks Today?
Yes! Starting with 16.8.0, React includes a stable implementation of React Hooks for:
- React DOM
- React DOM Server
- React Test Renderer
- React Shallow Renderer
Note that to enable Hooks, all React packages need to be 16.8.0 or higher . Hooks won’t work if you forget to update, for example, React DOM.
React Native will support Hooks in the 0.60 release .
Tooling Support
React Hooks are now supported by React DevTools. They are also supported in the latest Flow and TypeScript definitions for React. We strongly recommend enabling a new
lint rule called eslint-plugin-react-hooks
to enforce best practices with Hooks. It will soon be included into Create React App by default.
What’s Next
We described our plan for the next months in the recently publishedReact Roadmap.
Note that React Hooks don’t cover all
use cases for classes yet but they’revery close. Currently, only getSnapshotBeforeUpdate()
and componentDidCatch()
methods don’t have equivalent Hooks APIs, and these lifecycles are relatively uncommon. If you want, you should be able to use Hooks in most of the new code you’re writing.
Even while Hooks were in alpha, the React community created many interesting examples and recipes using Hooks for animations, forms, subscriptions, integrating with other libraries, and so on. We’re excited about Hooks because they make code reuse easier, helping you write your components in a simpler way and make great user experiences. We can’t wait to see what you’ll create next!
Testing Hooks
We have added a new API called ReactTestUtils.act()
in this release. It ensures that the behavior in your tests matches what happens in the browser more closely. We recommend to wrap any code rendering and triggering updates to your components into act()
calls. Testing libraries like
react-testing-library
can also wrap their APIs with it.
For example, the counter example fromthis page can be tested like this:
import React from 'react'; import ReactDOM from 'react-dom'; 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 effect act(() => { ReactDOM.render(<Counter />, container); }); 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 effect act(() => { button.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(label.textContent).toBe('You clicked 1 times'); expect(document.title).toBe('You clicked 1 times'); });
The calls to act()
will also flush the effects inside of them.
If you need to test a custom Hook, you can do so by creating a component in your test, and using your Hook from it. Then you can test the component you wrote.
To reduce the boilerplate, we recommend using
react-testing-library
which is designed to encourage writing tests that use your components as the end users do.
Thanks
We’d like to thank everybody who commented on the Hooks RFC for sharing their feedback. We’ve read all of your comments and made some adjustments to the final API based on them.
Installation
React
React v16.8.0 is available on the npm registry.
To install React 16 with Yarn, run:
yarn add react@^16.8.0 react-dom@^16.8.0
To install React 16 with npm, run:
npm install --save react@^16.8.0 react-dom@^16.8.0
We also provide UMD builds of React via a CDN:
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
Refer to the documentation for detailed installation instructions .
ESLint Plugin for React Hooks
Note
As mentioned above, we strongly recommend using the eslint-plugin-react-hooks
lint rule.
If you’re using Create React App, instead of manually configuring ESLint you can wait for the next version of react-scripts
which will come out shortly and will include this rule.
Assuming you already have ESLint installed, run:
# npm npm install eslint-plugin-react-hooks@next --save-dev # yarn yarn add eslint-plugin-react-hooks@next --dev
Then add it to your ESLint configuration:
{ "plugins": [ // ... "react-hooks" ], "rules": { // ... "react-hooks/rules-of-hooks": "error" } }
Changelog
React
- AddHooks — a way to use state and other React features without writing a class. ( @acdlite et al. in #13968 )
-
Improve the
useReducer
Hook lazy initialization API. ( @acdlite in #14723 )
React DOM
-
Bail out of rendering on identical values for
useState
anduseReducer
Hooks. ( @acdlite in #14569 ) -
Don’t compare the first argument passed to
useEffect
/useMemo
/useCallback
Hooks. ( @acdlite in #14594 ) -
Use
Object.is
algorithm for comparinguseState
anduseReducer
values. ( @Jessidhia in #14752 ) -
Support synchronous thenables passed to
React.lazy()
. ( @gaearon in #14626 ) - Render components with Hooks twice in Strict Mode (DEV-only) to match class behavior. ( @gaearon in #14654 )
- Warn about mismatching Hook order in development. ( @threepointone in #14585 and @acdlite in #14591 )
-
Effect clean-up functions must return either
undefined
or a function. All other values, includingnull
, are not allowed. @acdlite in #14119
React Test Renderer
- Support Hooks in the shallow renderer. ( @trueadm in #14567 )
-
Fix wrong state in
shouldComponentUpdate
in the presence ofgetDerivedStateFromProps
for Shallow Renderer. ( @chenesan in #14613 ) -
Add
ReactTestUtils.act()
for batching updates so that tests more closely match real behavior. ( @threepointone in #14744 )
ESLint Plugin: React Hooks
- Initial release . ( @calebmer in #13968 )
- Fix reporting after encountering a loop. ( @calebmer and @Yurickh in #14661 )
- Don’t consider throwing to be a rule violation. ( @sophiebits in #14040 )
Hooks Changelog Since Alpha Versions
The above changelog contains all notable changes since our last stable release (16.7.0). As with all our minor releases , none of the changes break backwards compatibility.
If you’re currently using Hooks from an alpha build of React, note that this release does contain some small breaking changes to Hooks. We don’t recommend depending on alphas in production code. We publish them so we can make changes in response to community feedback before the API is stable.
Here are all breaking changes to Hooks that have been made since the first alpha release:
-
Remove
useMutationEffect
. ( @sophiebits in #14336 ) -
Rename
useImperativeMethods
touseImperativeHandle
. ( @threepointone in #14565 ) -
Bail out of rendering on identical values for
useState
anduseReducer
Hooks. ( @acdlite in #14569 ) -
Don’t compare the first argument passed to
useEffect
/useMemo
/useCallback
Hooks. ( @acdlite in #14594 ) -
Use
Object.is
algorithm for comparinguseState
anduseReducer
values. ( @Jessidhia in #14752 ) - Render components with Hooks twice in Strict Mode (DEV-only). ( @gaearon in #14654 )
-
Improve the
useReducer
Hook lazy initialization API. ( @acdlite in #14723 )
Recommend
-
143
React v16.0September 26, 2017 by Andrew ClarkWe’re excited to announce the release of React v16.0! Among the changes are some long-standing feature requ...
-
125
React v16.0 发布
-
51
[译]React v16(新特性) Original 何蔷...
-
97
又一篇React实践【v16.0 +】icepy隐居山野的农夫
-
69
最大特征是支持Pointer Events在ReactDOM中添加以下事件。这是因为React发觉它在移动端的应用场景越来越多,外置的injectTapEventPlugin已经不够用了。有了这事件,以后大家往移动端堆应用更轻松。onPointerDownon…
-
15
Today we are releasing React 16.13.0. It contains bugfixes and new deprecation warnings to help prepare for a future major release. New Warnings Warnings for some updates during render A Rea...
-
10
Visual Studio 2019 v16.8 and v16.9 Preview 1 Release TodayVisual Studio 2019 v16.8 and v16.9 Preview 1 Release Today
-
6
Visual Studio 2019 v16.9 and v16.10 Preview 1 are Available Today!Visual Studio 2019 v16.9 and v16.10 Preview 1 are Available Today!
-
9
Visual Studio 2019 v16.10 and v16.11 Preview 1 are Available Today!
-
8
抖音 v16.1 for Android 去除广告无水印版...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK