Skip to content

06 RN - Context

State

Callbacks

State

Context API/Redux

State

Context vs Prop Drilling

Global/Context API vs Prop Drilling

State

When to Use Context

Context is designed to share data that can be considered "global" for a tree (or subtree) of React components.

Context is primarily used when some data needs to be accessible by many components at different nesting levels.

Context API

Create context

1
export const AppContext = React.createContext<IAppContext>(defaultValue);

Also creates Provider and Consumer.

Consumer is mainly used in class components.

1
2
export const AppContextProvider = AppContext.Provider;
export const AppContextConsumer = AppContext.Consumer;

Context Provider

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes

1
2
3
return (
      <AppContextProvider value={state} >
        <View style={styles.main}>

defaultValue from createContext is only used, when provider is not found!

All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. (same algorithm as Object.is)

Context Consumer

1
2
3
4
5
6
7
8
return (
            <AppContextConsumer>
                {appContext =>
                    <View style={styles.mainView}>
                        <Text>Board {appContext.moves}</Text>
                    </View>
                }
            </AppContextConsumer>
  • A React component that subscribes to context changes.
  • The function receives the current context value and returns a React node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.
  • If there is no Provider for this context above, the value argument will be equal to the defaultValue that was passed to createContext().

useContext hook

1
const value = useContext(AppContext);

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest above the calling component in the tree.

Mutating context

Include methods for updating the state in the Context object

1
2
3
4
5
export interface IAppContext {
    moves: number,
    changeMoves: (amount: number) => void,
    setMoves: (amount: number) => void,
}