React v16.3.0: New lifecycles and context API
A few days ago we wrote an article about the upcoming changes to our traditional lifecycle approach, including a step-by-step migration strategy. In React 16.3.0, we've added some new lifecycle methods to aid migration. We've also introduced new APIs for long-running request features: an official context API, a ref forwarding API, and a more semantic ref API.
Please read on to learn more about this release.
Officially certified Context API
For many years, React has provided an experimental API for Context. Although it is a powerful tool, its use is frowned upon due to problems inherent in the API, so we intend to replace this experimental API with a better API.
React 16.3 introduces a new Context API that is more efficient and supports static type checking and deep updates.
NOTE
The old ContextAPI will continue to be retained into React 16.x, so you will have time to migrate.
Here is an example of how to inject a "topic" using the new context API:
## by 司徒正美 const ThemeContext = React.createContext('light'); class ThemeProvider extends React.Component { state = {theme: 'light'}; render() { return ( <ThemeContext.Provider value={this.state.theme}> {this.props.children} </ThemeContext.Provider> ); } } class ThemedButton extends React.Component { render() { return ( <ThemeContext.Consumer> {theme => <Button theme={theme} />} </ThemeContext.Consumer> ); } }
createRef API
Previously, React provided two ways to manage refs: String ref API and callback ref API. Although the string ref API is more convenient, it has several disadvantages, so our official recommendation is to use callback ref.
React 16.3 provides a new solution for managing refs, which provides convenience for string refs and has no disadvantages:
## by 司徒正美 class MyComponent extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } render() { return <input type="text" ref={this.inputRef} />; } componentDidMount() { this.inputRef.current.focus(); } }
NoteExcept In addition to the new createRef API, callback refs will continue to be supported.
You don't need to replace callback refs in the component. They are slightly more flexible, so they will continue to be an advanced feature.
forwardRef API
Higher-order components (or HOCs) are a common way to reuse code between components. Based on the theme context example above, we might create a temporary object with the current "theme" injected as a property:
## by 司徒正美 function withTheme(Component) { return function ThemedComponent(props) { return ( <ThemeContext.Consumer> {theme => <Component {...props} theme={theme} />} </ThemeContext.Consumer> ); }; }
We can use the above special way to connect the component to the theme context without having to directly Use topic context. For example:
## by 司徒正美 class FancyButton extends React.Component { buttonRef = React.createRef(); focus() { this.buttonRef.current.focus(); } render() { const {label, theme, ...rest} = this.props; return ( <button {...rest} className={`${theme}-button`} ref={this.buttonRef}> {label} </button> ); } } const FancyThemedButton = withTheme(FancyButton); // We can render FancyThemedButton as if it were a FancyButton // It will automatically receive the current "theme", // And the HOC will pass through our other props. <FancyThemedButton label="Click me!" onClick={handleClick} />;
HOCs usually pass props to the component they wrap. Unfortunately, the refs didn't penetrate. This means that if we use a FancyThemedButton, we cannot add the ref to the FancyButton and therefore we cannot call focus().
The new proxy API solves this problem by providing a way to intercept a ref and forward it as a normal prop:
## by 司徒正美 function withTheme(Component) { // Note the second param "ref" provided by React.forwardRef. // We can attach this to Component directly. function ThemedComponent(props, ref) { return ( <ThemeContext.Consumer> {theme => ( <Component {...props} ref={ref} theme={theme} /> )} </ThemeContext.Consumer> ); } // These next lines are not necessary, // But they do give the component a better display name in DevTools, // e.g. "ForwardRef(withTheme(MyComponent))" const name = Component.displayName || Component.name; ThemedComponent.displayName = `withTheme(${name})`; // Tell React to pass the "ref" to ThemedComponent. return React.forwardRef(ThemedComponent); } const fancyButtonRef = React.createRef(); // fancyButtonRef will now point to FancyButton <FancyThemedButton label="Click me!" onClick={handleClick} ref={fancyButtonRef} />;
Changes in component lifecycle hooks
React’s class component API has been around for many years with little change. However, as we add support for more advanced features, such as error bounds and the upcoming asynchronous rendering mode, we extend this model in ways that it was not originally intended.
For example, in the current API, it is very easy to prevent the initial rendering by using some unusual means. In part, this is because there are so many hooks to accomplish this given task, and it's not clear which one is the best. We have noticed that the interrupt behavior of error handling is often not considered and can lead to memory leaks (this will also affect the upcoming asynchronous rendering mode). The current class component API also complicates other tasks, such as the work of our code optimizer (Prepack).
componentWillMount
, componentWillReceiveProps
, componentWillUpdate
These hooks can easily cause problems and seriously disrupt the React life cycle. For these reasons, we are deprecating these methods in favor of better alternatives.
We recognize that this change will impact many existing components. Therefore, the migration path will be as smooth as possible and migration options will be provided. (At Facebook, we have over 50,000 React components. We also rely on a progressive release cycle!
NOTEDeprecation warnings will be enabled in future versions of React 16 , are retained until 17 is released.
They can still be used even in React17, but they will be prefixed with "UNSAFE_" to indicate that they may cause problems. We have also prepared an automated script for this. Rename them in existing code
In addition to deprecating unsafe lifecycle hooks, we also added some new lifecycle hooks:
getDerivedStateFromProps
Used by componentWillReceiveProps.
##getSnapshotBeforeUpdate, used to safely read properties from the DOM before updating.
< ;StrictMode /> is a tool designed to expose potential problems. Like
,
will not. Rendered into a view. It can activate additional checks and warnings for its child components.
Note##.Checks are only available in development. mode; they will not affect production builds.
While strict mode may not catch all problems (such as certain types of tampering), it can help a lot of people if you run in strict mode. mode to see warnings, these things are likely to cause asynchronous rendering errors
In version 16.3, StrictMode helps:
Identify components with unsafe lifecycle hooks.
Warning about legacy string ref API usage.
Detect unexpected side effects
##
The above is the detailed content of React v16.3.0: New lifecycles and context API. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Context is the environment and status information when the program is executed. It can include a variety of information, such as the value of variables, the call stack of functions, the execution location of the program, etc., allowing the program to make corresponding decisions based on different contexts. and perform corresponding operations.

How to use context to implement request link tracking in Go. In the microservice architecture, request link tracking is a very important technology that is used to track the delivery and processing of a request between multiple microservices. In the Go language, we can use the context package to implement request link tracking. This article will introduce how to use context for request link tracking and give code examples. First, we need to understand the basic concepts and usage of the context package. The context package provides a mechanism

How to use context to implement request caching in Go Introduction: When building web applications, we often need to cache requests to improve performance. In the Go language, we can use the context package to implement the request caching function. This article will introduce how to use the context package to implement request caching, and provide code examples to help readers better understand. What is context? : In the Go language, the context package provides a way to pass between multiple goroutines

How to use context to implement request timeout control in Go Introduction: When we make network requests, we often encounter request timeout problems. A network request that does not respond for a long time will not only waste server resources, but also affect overall performance. In order to solve this problem, the Go language introduced the context package, which can be used to implement request timeout control. This article will introduce how to use the context package to implement request timeout control in Go, and attach corresponding code examples. 1. Understand the context package co

The context package in the Go language is used to pass request context information in the program. It can pass parameters, intercept requests and cancel operations between functions across multiple Goroutines. To use the context package in Go, we first need to import the "context" package. Below is an example that demonstrates how to use the context package to implement request parameter passing. packagemainimport("context"

How to use context to implement request retry strategy in Go Introduction: When building a distributed system, network requests will inevitably encounter some failures. In order to ensure the reliability and stability of the system, we usually use a retry strategy to handle these failed requests to increase the success rate of the request. In the Go language, we can use the context package to implement the request retry strategy. This article will introduce how to use the context package in Go to implement a request retry strategy, with code examples. 1. What is

How to use context to implement request encapsulation and decapsulation in Go. In the development of Go language, we often encounter situations where we need to encapsulate and decapsulate some request parameters. This situation is especially common in complex systems, where we need to pass request parameters to different functions and modules, and there may be nested calls between these functions and modules. In order to facilitate the management and delivery of these request parameters, we can use the context package in Go to implement request encapsulation and decapsulation. The context package is the Go language

The common application of context concepts in Java include "Servlet context", "Android context" and "Spring context": 1. In Java Web development, ServletContext refers to the context environment of the entire Web application; 2. In Android development , Context is a core Android system class; 3. In the Spring framework, ApplicationContext represents the Spring container context.
