Setup React Context With React Expo

Soufiane Oucherrou
3 min readJul 26, 2020

--

In a typical React application, data is passed top-down (parent to child) via props, but this may be cumbersome surely kinds of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides the way to share values like these between components without having to explicitly pass a prop through every level of the tree. source

Context

Context 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.

We’re going to implement very simple example of how to setup context and access to state from that context

App component

Now lets create a component called StateContext you can name it anything you want

  • line 1 we import createContext from react
  • line 4 we assign StateContext to createContext and we invoked it immediately
  • line 9 We will create a state called filmsusing the useState hook. The useState hook will return the current value of the filmsand a function which we can use to update the films.
  • line 12 we wrap everything with StateContext that we called in the line 4, Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. Accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.

Now time to go back to our main component in our case it called App , we rap everything with StateContext that we created earlier … Lets create other component to read to display all films

#FilmList

As you you notice we imported useContext from react, useContext 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 <StateContext.Provider> above the calling component in the tree.

If you fellowed with all the steps you will have access to state from Context, result below

Next we will see how to update Context from other component

To be continued…

--

--

No responses yet