1.

Explain new Context API in React 16?

Answer»

In React LAND, data is passed top-down from parent component to child component via PROPS. But many times props are needed by a component, which is more than 10 levels deep. In such a scenario, the middle components are just passing the props. This unnecessary passing of props is an issue and is called prop drilling. This is where state management like Redux and Flux comes into the picture, which maintains one single central state.

But with  Redux, the complexities of REDUCERS and middleware also comes.  It is good for a large application, but not for small or middle size applications.

Let’s FIRST look into the example by passing props through an unnecessary component. We have a GRANDFATHER component, which has a state called familyName. This is needed by  the Child component. But we also have  Father component in between, so we just pass familyName through it.

class GrandFather extends React.Component {  state = {    familyName: "Das"  }  render() {    return <Father familyName={this.state.familyName} />  } } const Father = ({ familyName}) => {  return <Child familyName={familyName} /> } const Child = ({ familyName }) => {  return <p>{familyName}</p> }

We can refactor the above to use the new Context API. Using Context means we don’t need to pass the familyName unnecessary through the  <Father /> component. Here first we create our  FamilyContext by React.createContext()

const FamilyContext = React.createContext({}); class GrandFather extends React.Component {  state = {    familyName: "Das"  }; render() {    return (      <FamilyContext.Provider value={this.state.familyName}>        <Father />      </FamilyContext.Provider>    );  } } const Father = () => {  return <Child />; }; const Child = () => {  return <FamilyContext.Consumer>{context => <p>{context}</p>} </FamilyContext.Consumer>; }; ReactDOM.render(<GrandFather />, document.querySelector("#app"))

Now, we will wrap the <Father /> component with <FamilyContext.Provider /> as it contains <Child />.Notice that the Provider has a value prop. Pass in whatever state you’d like to share to any Component deep down.

To have access to the familyName, we have also wrapped the <p> tag in the <FamilyContext.Consumer /> component so that it has access to the context.



Discussion

No Comment Found