React released version 16.4.2 today. As always, the K&C React development team is on a mission to keep you up to date with the latest versions of React. Here’s our guide to the new features present in the last two iterations of React – 16.3.0 and 16.4.2. And of course, if you would like to speak to one of K&C’s React or web development consultants please do get in touch!
The most anticipated feature of the React 16.3.0 release was the introduction of a new context API designed to be more efficient and support both deep updates and static type checking. It is well known that React has already tried multiple experimental APIs. However, they had an “unofficial” disclaimer attached to them and not recommended for use. So, after multiple experiments and debugging, it looks like React has finally managed to represent the updated API that will simplify state management without the need to resort to Redux / MobX.
The React store is built on top of the new context API.
Here is an example of a basic implementation.
import { initStore } from 'react-waterfall' const store = { initialState: { count: 0 }, actions: { increment: ({ count }) => ({ count: count + 1 }), }, } const { Provider, connect } = initStore(store) let Count = ({ count, actions }) => ( <> {count} <button onClick={actions.increment}>+</button> </> ) Count = connect(state => ({ count: state.count }))(Count) const App = () => ( <Provider> <Count /> </Provider> ) React.createContext(“Hello”)
instead of Redux in simple use cases;
Despite the React 16.3.0’s new Context API, there are still cases when you may need to use Redux. So, when do we need to use it and when to avoid?
Rule of thumb – “if you don’t know why you may need to use a Redux – DO NOT use it”
Let’s take a closer look at the advantages that the new API offers, as well as disadvantages that can be overcome with Redux.
Limited functionality. It doesn’t offer:
To summarize the above said, we’d say that the new Context app could be used for data flow in smaller apps, while in some cases you should stick to previous versions that will keep working for all React 16.x versions. However, with React 17 the old API will be deprecated, so don’t forget to migrate on time.
Previously, React alloweded for the management of refs in two different ways: through legacy string ref API and the callback API. Legacy strings had multiple significant downsides, like problems with async, render props or static typing, which is why React recommended to use callbacks.
In the new 16.3.0 version, in addition to callback refs, which will continue to be supported, React has eliminated all the downsides and introduced new createRef API, which can be an ergonomic alternative to callback refs.
class UserForm extends Component { constructor(props) { super(props); this.textInput = React.createRef(); } componentDidMount() { this.textInput.current.select(); } state = { username: 'Default' }; render() { return ( <div> Name: <input type = 'text' value={this.state.username} ref={this.textInput} onChange={this.handleUserChange} /> </div> ) } handleUserChange = () => { const input = this.textInput.current; this.setState({ username: input.value }) } }
Now, there’s also another new ref API that comes with the 16.3 version – the Object Ref API. It brings the simplicity of strings API combined with the stability of a callback ref API. Object refs should be a good fit in most cases Finally, another new API that was introduced is the forwardRef API, which enables a ref to be taken and forwarded as a normal prop. This ref can be used to access a nested element.
The React API evolves over time, which has led to a few problematic lifecycle methods that have meant bugs need to be eliminated and replaced by the newer API versions. Components that will soon be deprecated and prepended with UNSAFE are:
These methods have proven to be a source of confusion and bugs in the past and they also need to be deprecated in light of React’s steady movement towards Async Mode.
So what can we use instead? The React team offers the following migrations for the deprecated methods:
16.3 – Everything works as before
16.x – Everything works as before, but the deprecation warning will be added
17 – Still works with “UNSAFE_” prefix
Now let’s move to new methods that were introduced with React 16.3 release
-getDerivedStateFromProps
This method is actually static (ES6). Since it’s static, you can’t reference it, so whatever is returned from the method would be updated. It will be called on the initial mounting of the component, as well as when it’s re-rendered. This method is considered to be a safer alternative to the legacy componentWillReceiveProps. And in the version 16.4.0, the React developers managed to do so that every time under component rendering, getDerivedStateFromProps is now called every time regardless what caused the update.
class myComponent extends React.Component { state = { counter: 0 }; static getDerivedStateFromProps(nextProps, prevState) { if (prevState.counter !== nextProps.counter) { return { counter: nextProps.counter } } // Return null to indicate no change to state. return null; } }
-getSnapshotBeforeUpdate
This method is called right before any DOM mutations are made. It enables your component to capture current values (e.g. scroll position) before they are potentially changed. Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate(). Learn more about the getSnapshotBeforeUpdate() on the React’s official documents.
class ScrollingList extends React.Component { listRef = null; getSnapshotBeforeUpdate(prevProps, prevState) { // Are we adding new items to the list? // Capture the current height of the list so we can adjust scroll later. if (prevProps.list.length < this.props.list.length) { return this.listRef.scrollHeight; } return null; } componentDidUpdate(prevProps, prevState, snapshot) { // If we have a snapshot value, we've just added new items. // Adjust scroll so these new items don't push the old ones out of view. // (snapshot here is the value returned from getSnapshotBeforeUpdate) if (snapshot !== null) { this.listRef.scrollTop += this.listRef.scrollHeight - snapshot; } } render() { return ( <div ref={this.setListRef}> {/* ...contents... */} </div> ); } setListRef = ref => { this.listRef = ref; };
StrictMode is a component that does not render any visible API, but identifies potential issues in an app by activating supplementary checks and warnings for its descendants.For example, if to wrap strict component around problems component that contains many of the deprecated methods, you will see a number of warnings in your console advising you to make some changes.
To summarize, React’s 16.3 StrictMode helps to:
More features announced to be available in the upcoming releases of React.
React 16 (Fiber) laid the framework for Async rendering. In 16.3 release an experimental and unstable Async mode component has become available. The idea is that you can wrap any content any content which has less priority in AsyncMode component (unstable_AsyncMode) and get better performance.
Along with the React 16.3 release come new development tools to support debugging the new components. The new tools are available for both, Chrome and Firefox. These dev tools display AsyncMode, StrictMode, and the new Context API Components.
The React team has also added some pointer events, which are now available in React DOM:
But you should keep in mind that you may implement the mentioned event only in case your browser supports the Pointer Events specification.
Another issue the React team resolved in the latest version dealt with a vulnerability in the react-dom/serverimplementation, which existed in all following versions since the 16.0.0. This vulnerability affected server-rendered React apps and only those that contained the vulnerable pattern described below.
Your app might be affected by this vulnerability only if both of these two conditions are true:
More precisely, the vulnerable pattern is as follows:
let props = {}; props[userProvidedData] = "hello"; let element = <div {...props} />; let html = ReactDOMServer.renderToString(element);
To migrate, use React code mode scripts to add prefix for depreciation methods. By using polyfill from “react-lifecycle-compat” you will add backward compatibility to new methods.
In terms of timing, deprecation warnings will be enabled with a future 16.x releases, but the legacy lifecycles will continue to work until version 17. Even in version 17, it will still be possible to use them, but they will be aliased with an “UNSAFE_” prefix to indicate that they might cause issues. We have also prepared an automated script to rename them in existing code.