A React Context Consumer reads the current value from a React context and supplies it to a function that returns JSX. It helps avoid prop drilling when data must reach deeply nested components. section 10.1.1 section 10.1.3
Use a context consumer as follows:
- Create a context with createContext, optionally supplying a default value. section 10.1.3
- Place a matching context provider above the components that need the value. section 10.1.1
- Render Context.Consumer with a function as its only child; React invokes that function with the current context value. section 10.1.3
- Resolve the nearest matching provider, or receive the context default when no provider is found. section 10.6
Display a context value
function DisplayName() { return ( <p> <NameContext.Consumer> {(name) => name} </NameContext.Consumer> </p> ); } The child function is a render prop: it receives the current name and returns the paragraph content. In functional codebases, useContext is usually shorter and is preferred over the .Consumer property; .Consumer remains especially relevant in older class-based projects. section 10.1.3 section 10.6
