React js 16.3

Recently Facebook has released the react 16.3 which bundled with a few awesome features including Context API and createRef(), I will talk abit about Context API since its quite hot topic.

Context API its a feature that allows you to pass your data down to all child levels without passing props around like what you used to do. Lets take below code as example and we will convert to use Context API.

as you can see the top level pass in a prop call “color” from Animal Component > Cat Component > Color Component then finally received the prop and output in DOM, its ok for one or 2 props, but when your application grows and required to handle more props or stats, its going to be painful, luckily we can declare only once in Context API and color should received the props as child.

So lets get started.

first we need to declare that we want to use Context API, so lets just create a Context API (sorry by the time I create this, codesandbox is not using react 16.3):

  const AnimalContext = React.createContext(); // you can also add a default value inside createContext("your default value here")

AnimalContext comes with 2 component where we can use (Provider and Consumer) so the Provider will provide the data and Consumer will received the data, easy concept!

lets create our provider component and pass in the data.

const App = () => (
  
    
  
);

and you noticed that we have removed the prop “color” from Animal Component and add a keyword “value” in the provider component, value is the keyword that Provider provided where you store all your data here and pass it down. Now we want to add a Consume as discussed easier that Consumer will use to receive data. So Color is the component where we want to receive the context. Lets declare this in Color Component.

const Color = () => (
  
    {(contextValue) => (
      

I am {contextValue} 😸

)} );

easier that expected, and again you might notice, there is a function inside Consumer Component which is the pattern that Context API works, “contextValue” or any name you want to call which is the data / value keyword that passed from Provider, and of course you can use objects or functions… in value as example:

value={
  name: "some name",
  data: {...}
}

// use xxx.name to get the name from Consumer...

hope you enjoy this quick readup about context API.

Published by max

Web developer and Interaction Designer base in Singapore