ezzabuzaid / react-context-in-angular

1 stars 0 forks source link

How Does React Context API Work #6

Open ezzabuzaid opened 3 years ago

ezzabuzaid commented 3 years ago

Warning: I'll use React components 😏.

Context API comes with two important components, Provider and Consumer. Provider is the component that will pass a value for decedents consuming components. One provider can have multiple consumers and other providers.

Consumer, as you may have thought, will consume Provider value. React will go up the component tree starting from the Consumer component to find the nearest Provider and provide its value to that Consumer as callback style, if none is found a default value will be used instead. The Consumer will re-render whenever a Provider ancestor value changes.

To create context you simply call createContext passing default value if needed, a context object with Provider and Consumer components attached to it will return.

const MyContext = React.createContext('defaultValue');

The provider have value props that will passed down to the consumers.

function App() {
  return (
    <MyContext.Provider value="valueToBeConsumedByDescendantsConsumer">
      <ComponentThatHaveConsumerAsChild />
    </MyContext.Provider>
  );
}

The consumer takes a function with the Provider value as an argument, the function will be called (re-render 🙃) whenever the Provider value changes.

function ComponentThatHaveConsumerAsChild() {
  return (
    <MyContext.Consumer>
      {(value) => (<h1>{value}</h1>)}
    </MyContext.Consumer>
  );
}

You might want to know that this is not the only way to consume context, there's contextType and useContext, I won't cover them because those are applicable only to React way of doing things.

if you didn't get the whole picture, check the official docs, perhaps it would be more helpful.

Enough talking about React. It's time to code.