Entity Context

App Root

Context provides a way to pass data through the component tree without having to pass props down manually at every level

 

- React Docs

When to use

To share informations that can be considered "global" for a tree of React components

 

eg. current authenticated user, theme, or preferred language

 

...and state management, why not...

How it works

const MyContext = React.createContext(defaultValue);

Creates a new context object

 

When a component that uses the context is rendered, it will get the value from the closest matching provider

 

The defaultValue is used only when there is no matching providers

<MyContext.Provider value={/* some value */}>

Every Context object comes with a Provider component

 

The value prop is passed down to all consuming components

 

All consumers will re-render whenever the Provider’s value prop changes

// Class-based approach
<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>


// Hooks-based approach
const value = useContext(MyContext);

Subscribes to context changes

 

The value is equal to the value passed to the closest provider

 

The component will re-render if value changes

export const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222',
  },
};

export const ThemeContext = React.createContext(
  themes.dark // default value
);

Example

Theme context

function App() {
    const [currentTheme, setCurrentTheme] = useState('expedia');

    return (
        <Page>
            <Header>
                <ThemeSwitch onChange={setCurrentTheme} />
            </Header>
            <Main>
                <ThemeContext.Provider value={currentTheme}>
                    ...
                </ThemeContext.Provider>
            </Main>
        </Page>
    )
}

Example

App

function ForgottenButton({ children, onClick }) {
    const currentTheme = useContext(ThemeContext);

    return (
        <button onClick={onClick} className={`button theme-${currentTheme}`}>
            {children}
        </button>
    )
}

Example

Somewhere in the deepest of your app tree ...

React Context

By alenaksu

React Context

A very very very quick overview of the React context

  • 157