
Al igual que la gente está entusiasmada con la actualización de sus aplicaciones móviles y sistema operativo, los desarrolladores también deberían estar emocionados de actualizar sus marcos. La nueva versión de los diferentes marcos viene con nuevas características y trucos listos para usar.
A continuación se muestran algunas de las buenas características que debe considerar al migrar su aplicación existente a React 16 desde React 15.
¿Es hora de decir adiós React15?Manejo de errores

React 16 introduce el nuevo concepto de límite de error .
Los límites de error son componentes de React que detectan errores de JavaScript en cualquier parte de su árbol de componentes secundarios. Registran esos errores y muestran una interfaz de usuario alternativa en lugar del árbol de componentes bloqueado. Los límites de error detectan errores durante la renderización, en los métodos del ciclo de vida y en los constructores de todo el árbol debajo de ellos.
Un componente de clase se convierte en un límite de error si define un nuevo método de ciclo de vida llamado componentDidCatch(error, info)
:
Entonces puedes usarlo como un componente regular.
El componentDidCatch()
método funciona como un catch {}
bloque de JavaScript , pero para componentes. Solo los componentes de la clase pueden ser límites de error. En la práctica, la mayoría de las veces querrá declarar un componente de límite de error una vez. Luego lo usará en toda su aplicación.
Tenga en cuenta que los límites de error solo detectan errores en los componentes debajo de ellos en el árbol . Un límite de error no puede detectar un error en sí mismo. Si un límite de error falla al intentar representar el mensaje de error, el error se propagará al límite de error más cercano por encima de él. Esto también es similar a cómo catch {}
funciona el bloque en JavaScript.
Mira la demostración en vivo:
Para obtener más información sobre el manejo de errores, diríjase aquí.
Nuevos tipos de retorno de renderizado: fragmentos y cadenas
Deshazte de envolver el componente en un div mientras renderizas.
Ahora puede devolver una matriz de elementos del render
método de un componente . Al igual que con otras matrices, deberá agregar una clave a cada elemento para evitar la advertencia de clave:
render() { // No need to wrap list items in an extra element! return [ // Don't forget the keys :) First item , Second item , Third item , ];}
Comenzando con React 16.2.0, tiene soporte para una sintaxis de fragmento especial para JSX que no requiere claves.
Soporte para devolver cadenas:
render() { return 'Look ma, no spans!';}
Portales
Los portales proporcionan una forma de primera clase de convertir a los niños en un nodo DOM que existe fuera de la jerarquía DOM del componente principal.
ReactDOM.createPortal(child, container)
El primer argumento ( child
) es cualquier hijo React renderizable, como un elemento, cadena o fragmento. El segundo argumento ( container
) es un elemento DOM.
Cómo usarlo
Cuando devuelve un elemento del método de representación de un componente, se monta en el DOM como hijo del nodo principal más cercano:
render() { // React mounts a new div and renders the children into it return ( {this.props.children} );}
A veces es útil insertar un niño en una ubicación diferente en el DOM:
render() { // React does *not* create a new div. It renders the children into `domNode`. // `domNode` is any valid DOM node, regardless of its location in the DOM. return ReactDOM.createPortal( this.props.children, domNode );}
Un caso de uso típico de los portales es cuando un componente padre tiene un estilo overflow: hidden
o z-index
, pero necesita que el hijo "salga" visualmente de su contenedor. Por ejemplo, diálogos, tarjetas flotantes e información sobre herramientas.
Atributo DOM personalizado

React15 solía ignorar cualquier atributo DOM desconocido. Simplemente los omitiría ya que React no lo reconoció.
// Your code:
Representaría un div vacío al DOM con React 15:
// React 15 output:
En React16, la salida será la siguiente (se mostrarán los atributos personalizados y no se ignorarán en absoluto ):
// React 16 output:
Evite volver a renderizar con la configuración NULL en el estado

Con React16 puedes evitar actualizaciones de estado y re-renderizaciones directamente desde setState()
. Solo necesita que su función regrese null
.
const MAX_PIZZAS = 20;function addAnotherPizza(state, props) { // Stop updates and re-renders if I've had enough pizzas. if (state.pizza === MAX_PIZZAS) { return null; } // If not, keep the pizzas coming! :D return { pizza: state.pizza + 1, }}this.setState(addAnotherPizza);
Leer más aquí.
Crear referencias
Crear referencias con React16 ahora es mucho más fácil. Por qué necesita usar referencias:
- Administrar el enfoque, la selección de texto o la reproducción de medios.
- Activación de animaciones imperativas.
- Integración con bibliotecas DOM de terceros.
Refs are created using React.createRef()
and are attached to React elements via the ref
attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return ; }}
Accessing Refs
When a ref is passed to an element in render
, a reference to the node becomes accessible at the current
attribute of the ref.
const node = this.myRef.current;
The value of the ref differs depending on the type of the node:
- When the
ref
attribute is used on an HTML element, theref
created in the constructor withReact.createRef()
receives the underlying DOM element as itscurrent
property. - When the
ref
attribute is used on a custom class component, theref
object receives the mounted instance of the component as itscurrent
. - You may not use the
ref
attribute on functional components because they don’t have instances.
Context API
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
React.createContext
const {Provider, Consumer} = React.createContext(defaultValue);
Creates a { Provider, Consumer }
pair. When React renders a context Consumer
, it will read the current context value from the closest matching Provider
above it in the tree.
The defaultValue
argument is only used by a Consumer when it does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Note: passing undefined
as a Provider value does not cause Consumers to use defaultValue
.
Provider
A React component that allows Consumers to subscribe to context changes.
Accepts a value
prop to be passed to Consumers that are descendants of this Provider. One Provider can be connected to many Consumers. Providers can be nested to override values deeper within the tree.
Consumer
{value => /* render something based on the context value */}
A React component that subscribes to context changes.
Requires a function as a child. The function receives the current context value and returns a React node. The value
argument passed to the function will be equal to the value
prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the value
argument will be equal to the defaultValue
that was passed to createContext()
.
static getDerivedStateFromProps()
getDerivedStateFromProps
is invoked right before calling the render method. Both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
This method exists for rare use cases where the state depends on changes in props over time. For example, it might be handy for implementing a
Deriving state leads to verbose code and makes your components difficult to think about.
Make sure you’re familiar with simpler alternatives:
If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use
componentDidUpdate
lifecycle instead.If you want to re-compute some data only when a prop changes, use a memoization helper instead.
If you want to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a
key
instead.
This method doesn’t have access to the component instance. If you’d like, you can reuse some code between
getDerivedStateFromProps()
and the other class methods by extracting pure functions of the component props and state outside the class definition.
Note that this method is fired on every render, regardless of the cause. This is in contrast to
UNSAFE_componentWillReceiveProps
. It only fires when the parent causes a re-render and not as a result of a local setState
.
We compare
nextProps.someValue
with this.props.someValue.
If both are different then we perform some operation, setState
static getDerivedStateFromProps(nextProps, prevState){ if(nextProps.someValue!==prevState.someValue){ return { someState: nextProps.someValue}; } else return null;}
It receives two params
nextProps
and prevState
. As mentioned previously, you cannot access this
inside this method. You’ll have to store the props in the state to compare the nextProps
with previous props. In above code nextProps
and prevState
are compared. If both are different then an object will be returned to update the state. Otherwise null
will be returned indicating state update not required. If state changes then componentDidUpdate
is called where we can perform the desired operations as we did in componentWillReceiveProps
.
Bonus: React Lifecycle events

Original text

Lifecycle credits — //twitter.com/dceddia
Well these are some of the features that you should definitely try while working with React16!
Happy coding ? ?