Graduate Program KB

React Context

  • Provides a way to pass data from component tree without passing props manually on every level. Can share data between components that are not directly connected.
  • Provider: allows us to declare the data that we want available throughout our component tree.
  • Consumer: allows any component in the component tree that needs that data to be able to subscribe to it.
  • Example
    //Creating the Context
    //Can also have a default value, createContext("Default")
    export const localeContext = React.createContext();

    //Using the Context
    import {localeContext} from './LocaleContext';
    
    const App = () => {
        const locale = 'en';

        return (
            <localeContext.Provider value ={locale}>
            </localeContext.Provider>
        )
    }