Prop Drilling
Prop drilling is the process to get data to parts of the React Component tree, and Context API provides a way to share values between different Components, without having to explicitly pass a prop through every level. The context API allows better performance.
UseContext
“useContext” hook is used to create common data that can be accessed throughout the component hierarchy without passing the props down manually to each level. Context defined will be available to all the child components without involving “props”. The context is used to manage global data.
Example: global state, theme, services, user settings, and more.
- Create context using the createContext method
- Take your created context and wrap the context provider around your component tree.
- Put any value you like on your context provider using the value prop.
- Read that value within any component by using the context consumer.
Three simple steps: createContext, Provider and Consumer
1. createContext
createContext outside any components to create one or more contexts. By default, the values they receive will be the default values you have specified when creating the context. The useContext also makes sure to re-render the component when the context value changes. createContext lets you create a context that components can provide or read.
2. Provider
The Provider component accepts a value prop to be passed the consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree. To pass multiple values in React Context, we can use the Provider API. Also, we can easily consume the context data by utilizing the useContext React Hook.
3. Consumer
The Consumer component that uses a rendering function provided as a child component of Context. A special consumer component available in context. A single context has as many consumers as needed. When the context value changes (by changing the value prop of the provider <Context.Provider value = {value} />), then all consumers are immediately notified and re-rendered.
Conclusion
- “useContext” is an amazing way to eliminate the overhead of passing data to various level in the hierarchy via props, even if it’s not needed.
- Try updating to React Hooks at some point. This is an interesting feature and may make you think more about functional programming.