An overview of the

The React team released the latest version 16.9 on August 9. Here’s a quick look at what changes are in and what to look out for.

The key changes are as follows:

  • Used in version 16.9componentWillMount,componentWillReceivePropsandcomponentWillUpdateYou will receive warnings from React.
  • For large React applicationsReact.ProfilerFor performance evaluation
  • usejavascript:React will throw a warning, and this will be banned in future major releases.
  • abandonedFactorycomponent
  • For testingact()Method formally supports asynchrony

Unsafe Life cycle

In version 16.3, the React team discussed these three potential lifecycle issues and added the UNSAFE_ prefix as their alias in version 16.3. As planned, a warning would be issued in version 16.9. All three life cycles for componentWillMount were removed completely in major release 17.0.

  • ComponentWillMount –UNSAFE_componentWillMount
  • ComponentWillReceiveProps –UNSAFE_componentWillReceiveProps
  • ComponentWillUpdate –UNSAFE_componentWillUpdate
What does that mean for the old project?

It’s not that big of a deal, the official guarantee is that even in 17.0, the life cycle using UNSAFE_ will work, just the name of the life cycle function has been changed. To avoid warning when an old project is upgraded, you can manually change the function name. Of course, you can also use the official tool codemod to make one-click changes:

cd your_project
npx react-codemod rename-unsafe-lifecycles
Copy the code

Development teams can also add StrictMode

to their projects to prohibit the use of such potentially risky life cycles.

Use React.Profiler for performance evaluation

The React 16.9 update provides a way to programmatically collect measured code. <React.Profiler> is commonly used in large React projects.

It can be added as a node anywhere in the React application and can evaluate how often the React application renders and the “cost” of rendering. The goal is to help identify parts of the application that are rendering slowly, and may make optimizations like Memoization easier

render( <App> <Profiler id="Navigation" onRender={callback}> <Navigation {... props} /> </Profiler> <Main {... props} /> </App> );Copy the code

Profilers can be used in multiple places or nested. It takes two parameters, ID and onRender. OnRender is used during the Commit phase of the React update, which is the last phase of the internal update. In this phase React moneizes all updates and feeds them back to the DOM. OnRender also brings back some performance parameters for this update when triggered:

  • Id, used to distinguish between multiple pofilers, passed in by props
  • Phase, with a value of “mount” or “update”, indicates whether the current component tree is being mounted for the first time or in an update cycle.
  • ActualDuration, the time it takes to update the current component tree, is significantly reduced using component caching methods such as React.memo
  • BaseDuration, the time to initially mount the component tree, can be interpreted as the time to render without any optimization
  • StartTime, the initial timestamp of this update
  • CommitTime, the end timestamp of this update (until the commit phase expires)
  • Interactions’ schedule stack for this update

Armed with the callback information from the component updates above, we can more precisely determine the benefits of the optimization method used.

It is important to note that profilers, even though they are lightweight components, still have performance and computing overhead and are not recommended in production environments.

The ACT () method used for testing officially supports asynchrony

React provides a built-in library for testing components, react-dom/test-utils. In order to better simulate the real behavior of browsers and users in the test environment, act() has the ability to make asynchronous calls and centrally handle state changes in the context of community wishes. In previous versions, writing asynchronous code (asynchronous status updates) in act () would throw the following warning

An update to SomeComponent inside a test was not wrapped in act(…) .

In React 16.9, act() also supports asynchronous functions and can use await:

await act(async () => {
  // ...
});
Copy the code

The React team strongly recommends providing test cases for your components. In this article, we provide some tips and scenarios for using act(), as well as scenarios for testing hooks, such as events that test a hook:

import React, { useState } from "react";

export default function Toggle(props) {
  const [state, setState] = useState(false);
  return (
    <button
      onClick={()= >{ setState(previousState => ! previousState); props.onChange(! state); }} data-testid="toggle" > {state === true ? "Turn off" : "Turn on"}</button>
  );
}
Copy the code

Here’s a test example

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";

import Toggle from "./toggle";

let container = null;
beforeEach((a)= > {
  // setup a DOM element as a render target
  container = document.createElement("div");
  // container *must* be attached to document so events work correctly.
  document.body.appendChild(container);
});

afterEach((a)= > {
  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

it("changes value when clicked", () = > {const onChange = jest.fn();
  act((a)= > {
    render(<Toggle onChange={onChange} />, container);
  });

  // get a hold of the button element, and trigger some clicks on it
  const button = document.querySelector("[data-testid=toggle]");
  expect(button.innerHTML).toBe("Turn off");

  act(() => {
    button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
  });

  expect(onChange).toHaveBeenCalledTimes(1);
  expect(button.innerHTML).toBe("Turn on");

  act(() => {
    for (let i = 0; i < 5; i{+ +)button.dispatchEvent(new MouseEvent("click", { bubbles: true})); }});expect(onChange).toHaveBeenCalledTimes(6);
  expect(button.innerHTML).toBe("Turn on");
});

Copy the code

These examples use the native DOM API, but you can also use the React Testing Library to reduce boilerplate code. Many of its methods are already implemented through act()

Deprecate javascript: Form insecure urls

React will raise a warning if the href of the a tag uses javascript: in version 16.9

const userProfile = {
  website: "javascript: alert('you got hacked')"}; // This will now warn: <a href={userProfile.website}>Profile</a>Copy the code

And it will throw errors in future major releases, which will ban this vulnerability

Deprecating the Factory component

Before Babel became a mainstream compiler for JavaScript classes, you could write a “factory” in React to create a component that used the Render method to return an object

function FactoryComponent() {
  return { render() { return <div />; }}}Copy the code

This approach is confusing because it looks like a function component, which it isn’t. React support for it will cause libraries to become large and slow. As a result, this pattern is being deprecated in 16.9 and warnings are being printed when encountered. If the project depends on this component, can add FactoryComponent.prototype=React.Com ponent. The prototype for compatibility.

changlog

React

  • Provides a < react. Profiler> API implementation to programmatically evaluate performance. (@bvaughn in #15172)

  • Remove unstable_ConcurrentMode to support unstable_createRoot. (@acdlite in #15532)

React DOM

  • Discard the old lifecycle method starting with UNSAFE_*. (@bvaughn in #15186 and @threepointone in #16103)

  • Ditch javascript: form urls. (@sebmarkbage in #15047)

  • Deprecate uncommon “Module Pattern” (Factory) components. (@sebmarkbage in #15145)

  • Add support for the disablePictureInPicture property on the Video component. (@eek in #15334)

  • Added support for onLoad events for Embed. (@cherniavskii in #15614)

  • Support for editing useState state in DevTools. (@bvaughn in #14906)

  • Support for switching Suspense in DevTools. (@gaearon in #15232)

  • A warning is issued when setState is looped in useEffect. (@gaearon in #15180)

  • Fix memory leaks. (@paulshen in #16115)

  • Fix crashes using findDOMNode in components for Suspense wraps. (@acdlite in #15312)

  • Fix pending effect due to refresh too late. (@acdlite in #15650)

  • Fix incorrect parameter order in warning messages. (@brickspert in #15345)

  • Fix when present! Hide problems with Suspense degraded nodes when using the important style. (@acdlite in #15861 and #15882)

  • Improve your performance with Chocolate. (@bmeurer in #15998)

React DOM Server

  • Fixed error output for camelCase custom CSS property names. (@bedakb in #16167)

  • React Test Utilities and Test Renderer

  • Add the act (async () = >…). To test asynchronous status updates. (@threepointone in #14853)

  • Added support for nested acts for different renderers. (@threepointone in #16039 and #16042)

  • In strict mode, a warning is issued if a side effect function is called outside the ACT. (@threepointone in #15763 and #16041)

  • Alerts when using act in the wrong renderer. (@threepointone in #15756)


Pay attention to [IVWEB community] public number to get the latest weekly articles, leading to the top of life!