Passing data between screens in React Native with useContext()hook.
In this blog I will teach the easiest way to pass the data between screens(components) in your React Native app. For demonstration I am going to use a simple app with 2 screens: LoginScreen and HomeScreen. The goal is to pass currentUser from LoginScreen to the Home screen.
It will be easier if I skip the code for the login process (loginHandler, http request for user autentication, TextInput and etc), so lets assume we already have a currentUser object.
With useContext() hook we can easily pass the data to any component in a React application. So how does it work?
- Create new .js file. In my example I called it UserContext.js
- Create React Context Object with initial value and export it.
UserContext.jsimport React from 'react';const userData = React.createContext({user: null});export default userData
3. In the component from which you want to transfer data import userData object.
4. Provide userData object with a value (in our case the value is currentUser).
Login.jsimport React from 'react';
import userData from './UserContext.js'export default function Login(){
const currentUser = {name: "John", lastName: "Smith"} return (
<userData.Provider value={{user: currentUser}}>
{/* Provider is passing a value to userData object */}
)
}
By the way if the value changes (currentUser) the component will re-render.
5. Import useContext hook on top of the file.
6. Import userData.
7. Pass userData object to useContext() hook.
HomeScreen.jsimport React, {useContext} from 'react';
import {Text, View} from 'react-native';
import userData from './UserContext.js'export default function Home(){ const data = useContext(userData); return (
<View>
<Text>Welcome {data.name} {data.lastName}!</Text>
</View>
)
}
This is it. Using useContext() hook we rendered currentUser name on the HomeScreen.