Manejo de estado con Context y Hooks en React

Osman Cea
NodersJS
Published in
8 min readSep 23, 2019

--

La “nueva” API de Context de React (disponible desde la versión 16.3) nos permite encapsular un pedazo de estado en un contexto que es inyectable en cualquier lugar de nuestro árbol de componentes. Por ejemplo:

import React from 'react';const AlbumOfTheWeek = React.createContext({
title: 'Pop Food',
artist: 'Jack Stauber',
genre: 'Edible Pop', // lol
});
export default AlbumOfTheWeek;

Luego podemos consumir los valores provistos por AlbumOfTheWeek en cualquier lugar de nuestra aplicación a través de un consumidor utilizando render props:

import React from 'react';
import ReactDOM from 'react-dom';
import AlbumOfTheWeek from './context/album-of-the-week';function App() {
return (
<UserProfile />
);
}
function UserProfile() {
return (
<section>
<h1>Hi I'm Osman and this is my album of the week:</h1>
<AlbumOfTheWeek.Consumer>
{album => (
<dl>
<dt>Title:</dt>
<dd>{album.title}</dd>
<dt>Artist:</dt>
<dd>{album.artist}</dd>
<dt>Genre:</dt>
<dd>{album.genre}</dd>
</dl>
)}
</AlbumOfTheWeek.Consumer>
</section>
);
}

--

--