Yesterday, Dan Abramov, one of the React developers, announced the release of React 16.8, which comes with the feature everyone was waiting for, “Hooks”. This feature first landed in React 16.7-alpha last year and now it is available in this stable release.
This stable implementation of React Hooks is available for React DOM, React DOM Server, React Test Renderer, and React Shallow Renderer. Hooks are also supported by React DevTools and the latest versions of Flow, and TypeScript. Developers are recommended to enable a new lint rule called eslint-plugin-react-hooks that enforces best practices with Hooks. It will also be included in the Create React App tool by default.
What are Hooks?
At the React Conf 2018, Sophie Alpert and Dan Abramov explained what are the current limitations in React and how they can be solved using Hooks. React Hooks are basically functions that allow you to “hook into” or use React state and other lifecycle features via function components. Hooks comes with various advantages such as enabling easy reuse of React components, splitting related components, and use React without classes.
What’s new in React 16.8?
Currently, Hooks do not support all use cases for classes, but soon it will. Only two methods, that is, getSnapshotBeforeUpdate() and componentDidCatch(), don’t have their Hooks API counterpart.
A new API named ReactTestUtils.act() is introduced in this stable release. This API ensures that the behavior in your tests matches what happens in the browser more closely. Dan Abramov in a post recommended wrapping code rendering and triggering updates to their components into act() calls.
Other changes include:
- The useReducer Hook lazy initialization API is improved
- Support for synchronous thenables is added to React.lazy()
- Components are rendered twice with Hooks in Strict Mode (DEV-only) similar to class behavior
- A warning is shown when returning different hooks on subsequent renders
- The useImperativeMethods Hook is renamed to useImperativeHandle
- The Object.is algorithm is used for comparing useState and useReducer values
To use Hooks, you need to update all the React packages to 16.8 or higher. On a side note, React Native will support Hooks starting from React Native 0.59 release.
Read all the updates in React 16.8 on their official website.