Steps to Create Context inside React Native Project
Inside your project folder create a new folder name
helpers
Inside
helpers directory
, create a file namedcontext.js
Inside
context.js
, type...
import React from 'react';
export const AuthContext = React.createContext();
- To use your context, import
context.js
inApp.js
...
import {AuthContext} from './helpers/context';
...
- In
App.js
, use React.useMemo
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 useauthContext
as the value of yourAuthContext.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 :)
ย