Docs / rescript-react / useContext Hook
Edit

useContext

Context provides a way to pass data through the component tree without having to pass props down manually at every level. The useContext hooks gives access to such Context values.

Note: All the details and rationale on React's context feature can be found in here.

Usage

RES
let value = React.useContext(myContext)

Accepts a React.Context.t (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

Examples

A Simple ThemeProvider

ReScriptJS Output
// App.res
module ThemeContext = {
  let context = React.createContext("light")

  module Provider = {
    let make = React.Context.provider(context)
  }
}

module ThemedButton = {
  @react.component
  let make = () => {
    let theme = React.useContext(ThemeContext.context)
    let (color, backgroundColor) = switch theme {
    | "dark" => ("#ffffff", "#222222")
    | "light" | _ => ("#000000", "#eeeeee")
    }

    let style = ReactDOMStyle.make(~color, ~backgroundColor, ())

    <button style> {React.string("I am a styled button!")} </button>
  }
}

module Toolbar = {
  @react.component
  let make = () => {
    <div> <ThemedButton /> </div>
  }
}

@react.component
let make = () => {
  <ThemeContext.Provider value="dark">
    <div> <Toolbar /> </div>
  </ThemeContext.Provider>
}