React ~ Component Patterns ~ React Context - rohit120582sharma/Documentation GitHub Wiki

Whenever you’re utilising a component architecture, as your application grows, the ability to share state amongst different components will become an issue.

Context API provides a way to pass data through the component tree without having to pass props down manually at every level, no prop-drilling. It is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

Prop-drilling is the condition where you find yourself having to pass down props through components that don't use those props just to get them to the appropriate child components.

It requires 3 following things:

Create a context

We access this API using React.createContext() which returns an object that has two components.

// Create a context for the locale with the default value
const LocaleContext = React.createContext({
    locale: 'en',
    toggleLocale: () => {}
});

Provider

Provider allows us to “declare the data that we want available throughout our component tree”.

You use Provider just like you would any other React component. It accepts a value prop which is the data that you want available to any of its children who need to consume it.

Now, any component in our component tree that needs the value of locale will have the option to subscribe to it using LocaleContext.Consumer.

import LocaleContext from './LocaleContext';

class App extends React.Component {
    const state = {
        locale: 'en',
        toggleLocale: () => {
            this.setState(prevState => ({
                locale: prevState.locale === 'en' ? 'es' : 'en'
            }));
        }
    }

    return (
        <LocaleContext.Provider value={this.state}>
            <Home />
        </LocaleContext.Provider>
    );
}

Consumer

Consumer allows “any component in the component tree that needs that data to be able to subscribe to it”.

Again, the whole point of the Consumer component is that it allows you to get access to the data that was passed as a value prop to the Context’s Provider component.

All Consumers are re-rendered whenever the Provider value changes. Changes are determined by comparing the new and old values using the same algorithm as Object.is.

The consumer uses render prop API which means it requires a function as a child. The function receives the current context value and returns a React node.

import LocaleContext from './LocaleContext';

function Blog(props) {
    return (
        <LocaleContext.Consumer>
            { ({locale, toggleLocale}) => <Posts locale={locale} /> }
        </LocaleContext.Consumer>
    );
}


⚠️ **GitHub.com Fallback** ⚠️