Understanding the useContext design
React provides a useContext
hook to consume a context:
import UserContext from './UserContext' const Title = () => { const user = useContext(UserContext) return <div>{user.name}</div> }
The useContext
hook function takes one input argument, context
, and returns the shared value. context
is normally imported from a definition file.
useContext data structure
We are going to explain how useContext
is designed with a stripped-down version of the source code. Let's take a look at the data structure that makes it happen:
To consume (or read) a context value, each fiber gets a new dependencies
property to keep track of all the context it consumes. This is because a component can use multiple useContext
and each usage consumes a different context, such as UserContext
and ThemeContext
.
The dependencies...