This is the latest docs version
Quick Links
  • -Overview
  • -Language Features
  • -JS Interop
  • -Build System
Documentation
Language Manual
Reference for all language features
ReScript & React
First class bindings for ReactJS
GenType
Seamless TypeScript integration
Reanalyze
Dead Code & Termination analysis
Exploration
Packages
Explore third party libraries and bindings
Syntax Lookup
Discover all syntax constructs
APIPlaygroundBlogCommunity
  • Playground
  • Blog
  • Twitter
  • GitHub
  • Forum
rescript-react
Overview
  • Introduction
  • Installation
  • Migrate from JSX v3
Main Concepts
  • Elements & JSX
  • Rendering Elements
  • Components and Props
  • Arrays and Keys
  • Refs and the DOM
  • Context
  • Styling
  • Router
  • Lazy Components
Hooks & State Management
  • Hooks & State Management Overview
  • useEffect Hook
  • useState Hook
  • useReducer Hook
  • useContext Hook
    • Usage
    • Examples
  • useRef Hook
  • Build A Custom Hook
Guides
  • Beyond JSX
  • Forwarding Refs
  • Extensions of props
Docs / rescript-react / useContext Hook
Edit

You are currently looking at the v0.12.0 docs, which are still a work in progress. If you miss anything, you may find it in the older v0.11.0 docs here.

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>
}
useReducer HookuseRef Hook

© 2024 The ReScript Project

Software and assets distribution powered by KeyCDN.

About
  • Community
  • ReScript Association
Find us on