New in React 16.3: an Official Context API, Better Component Lifecycle Methods, More
React v16.3.0 was announced last week by Facebook, which originally developed the library for internal usage and then open sourced the project, while continuing to lead development efforts.
Core React JS team member Brian Vaughn highlighted an official context API that replaces an "experimental" API that has been offered for years but rarely promoted because of inherent issues "and because we always intended to replace the experimental API with a better one."
That "better one" is more efficient and supports both static type checking and deep updates, though the old experimental API will be available throughout the React 16.x lifecycle.
The context API lets developers streamline the access to data provided to React components. Typically, such data is passed down from one level of a component tree to the next through use of props. To use data, a React component needs to access it via passed-on props or through the setting of state.
With the new context API, data required by many components of a project can be accessed without having to be passed down through multiple component levels, ideal for working with things like locale preferences, authenticated users, UI themes and so on. In effect, it provides a global context from which a tree of React components can access data directly.
However, Facebook warns not to use the new functionality too liberally: "Don’t use context just to avoid passing props a few levels down. Stick to cases where the same data needs to be accessed in many components at multiple levels."
The new release also includes new methods for managing the lifecycle of components, because existing methods for letting developers insert logic code at different steps -- such as before a component will be mounted or updated or receive props -- were deemed "to encourage unsafe coding practices."
"A few days ago, we wrote a post about upcoming changes to our legacy lifecycle methods, including gradual migration strategies," Vaughn said in last week's post. "In React 16.3.0, we are adding a few new lifecycle methods to assist with that migration."
Other new features include new APIs for working with refs, which provide a way to access DOM nodes or React elements created in the render method responsible for the display of all components.
All of the above and many more new features are detailed in the project's GitHub site.
David Ramel is the editor of Visual Studio Magazine.