Using Context In React Native
Solution 1:
React Native uses the same react
package used for web applications. All React Native components work in the same way as the React ones (in terms of creation, lifecycle and the API, the main difference being that they do not render HTML elements, but custom components that then talk to the OS API), so you can use context in the same way you do in React. In fact, the F8 App makes use of the context functionality in order to handle the back button in Android. Have a look at the source code.
Solution 2:
Hey there here is an example of context in react native that Ive used for authentication in one of my projects, centralizing the authentication the methods can then be imported into the relevant screens for example signIn, signUp or [user, setUser] =useState().
import React, {createContext, useState} from 'react';
export const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
return(
<AuthContext.Providervalue = {{user,
setUser,
LoginWithEmail:async (user, success_callback, failed_callback) => {
......
},
SignupWithEmail: (email, password) => {
....
},
Signout: () => {
.....
},
checkIfLoggedIn : user => {
.....
},
contactpage : (email, message, name, phone) => {
.....
},
forgotPassword : (email) => {
.....
},
logout: async () => {
....
},
}}>
{children}
</AuthContext.Provider>
);
};
and then you can pass in context using this in your relevant screens:
const {LoginWithEmail} = useContext(AuthContext);
const {signUpWithEmail} = useContext(AuthContext);
const {user, setUser} = useContext(AuthContext);
Post a Comment for "Using Context In React Native"