search
HomeBackend DevelopmentPHP TutorialReact 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();
  }
}
Note

Except 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></component>}
      </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>

        {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></fancythemedbutton>;

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></component>
        )}
      </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></fancythemedbutton>;

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!

NOTE

Deprecation 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 component

< ;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:

  1. Identify components with unsafe lifecycle hooks.

  2. Warning about legacy string ref API usage.

  3. 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.