Implement Context in React Native

Implement Context in React Native

Steps to Create Context inside React Native Project

  • Inside your project folder create a new folder name helpers

  • Inside helpers directory, create a file named context.js

  • Inside context.js, type...

import React from 'react';

export const AuthContext = React.createContext();
  • To use your context, import context.js in App.js
...
import {AuthContext} from './helpers/context';
...

const App: () => Node = () => {

...
  const authContext = React.useMemo(() => ({
    signIn: () => {
      setToken(token);
    },
    signOut: () => {
      seTToken(token);
    },
  }));

  return (
    <AuthContext.Provider value={authContext}>
      ...
    </AuthContext.Provider>
  )

...
}


export default App;

In this scenario, let say you are creating an authentication system inside your app. using React.useMemo it will create dynamic functions that you can use all over your app. To use this capability, you need to use authContext as the value of your AuthContext.Provider

  • To use the capability of our Context, create a new component called Login.js. In Login.js, import AuthContext again
...
import React from 'react';
import {AuthContext} from '../../helpers/context';



const LoginScreen: () => Node = () => {
  ...
  const {signIn} = React.useContext(AuthContext)
}
  • Now you can use the signIn() function via pressing of button

I hope you enjoy :)

ย