In React, createContext()
allows to create global variables:
jsximport React, { createContext } from 'react'; const user = { name: 'Erik', age: 29, city: 'Barcelona' } const UserContext = createContext(user); export default UserContext;
After creating the context, we can access to the user properties from a component:
jsximport React, { useContext } from 'react'; import 'UserContext' from './UserContext'; const Profile = () => { const user = useContext(UserContext); return( <div className = 'User'> {user.name} is {user.age} years old and comes from {user.city}. </div> ); } export default Profile;
Since we can use useContext
in independent components, it avoids the need to pass props to children and grandchildren.
But what happens if the user data is dynamic instead of static? Perhaps we need to fetch user's data from a database.
In this case, we would create the context first:
jsximport React, { createContext } from 'react'; const UserContext = createContext(); export default UserContext;
Then, we would create a component to fetch data:
jsximport React, { useEffect, useState } from 'react'; import UserContext from './UserContext'; const User = () => { const [user, setUser] = useState({}); useEffect( () => { let user = getDataFromDatabase(); setUser(user); }, []); return( <UserContext.Provider value = {{user}}> <Profile/> <UserContext.Provider> ); } export default User;
It's important to notice that we need to pass the dynamic object into the provider.
At this point, we are able to access the user properties:
jsximport React, { useContext } from 'react'; import 'UserContext' from './UserContext'; const Profile = () => { const { user } = useContext(UserContext); return( <div className = 'User'> {user.name} is {user.age} years old and comes from {user.city}. </div> ); } export default Profile;
In this example, we are working only with one children. When there are several children and grandchildren, it's even more convenient to use useContext
, because it will simplify the code. Again, we won't need to use props.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.