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}>

or

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

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

useContext hook

1
const value = useContext(AppContext);

Accepts a context object (the value returned from React.createContext) and returns the current context (from provider) 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,
}

Use regular state in upper/root component and provide value for update function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const App = () => {
  const [state, setState] = useState(defaultValue);

  const updateMovesFn = (amount: number) => {
    setState({...state, moves: state.moves + amount});
  };

  return (
    <AppContext.Provider value={{...state, changeMoves: updateMovesFn}}>
      <View