React Context

Why?

  • instead of prop drilling, use react context to tunnel props to children components implicitly
  • consume it on demand, top level component provides information in the context
  • example use cases
    • theme provider with children of children consuming theme
    • firebase instance at top level of react components
    • authentication

How?

  • create react context1
    • access to provider and consumer component
import React from 'react'
const FirebaseContext = React.createContext(null)
export default FirebaseContext
  • value given to provider can be component state or props
import App from './components/App'
import Firebase, { FirebaseContext } from './components/Firebase'
ReactDOM.render(
<React.StrictMode>
<FirebaseContext.Provider value={new Firebase()}>
<App />
</FirebaseContext.Provider>
</React.StrictMode>,
document.getElementById('root')
)
  • children of children component can consume context
import { FirebaseContext } from '../Firebase'
const Home = () => (
<FirebaseContext.Consumer>
{firebase => {
return <div>I've access to Firebase and render something</div>
}}
</FirebaseContext.Consumer>
)

When to use?

  • component hierarchy grows vertically in size
  • prop drilling appears in code base, refactor and use context
  • advanced state management with React Hooks
    • shared and global state
  • use [useContext Hook] instead of Consumer component

To Review