ReasonReact

ReasonReact

  • Docs
  • Try
  • Examples
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Core

Getting Started

  • What & Why
  • Installation
  • Intro Example

Core

  • Components
  • JSX
  • Event
  • Style
  • Router
  • ReactDOM
  • Refs in React
  • Testing components

Hooks

  • useState
  • useReducer
  • useEffect
  • Custom Hooks

ReactJS Idioms Equivalents

  • Invalid Prop Name
  • Props Spread
  • Component as Prop
  • Ternary Shortcut
  • Context
  • Error boundaries

FAQ

  • I'm Having a Type Error
  • I Really Need Feature X From ReactJS
  • I want to create a DOM element without JSX
Edit

Refs in React

Not to be confused with Reason ref, the language feature that enables mutation.

Refs in React come in two forms. One works a lot like Reason ref - it is an object with a single field current that gets mutated. The other is a function which gets called whenever the ref value changes. ReasonReact works with both. React.Ref.t is the ref with a value that mutates. You create this kind of ref with the useRef hook or with createRef in the Record API.

There are many cases where you might want to use refs to track things that don't necessarily need to trigger a re-render but are useful for logging or some other side effect. In this case you can use useRef with any value you'd like to track!

[@react.component]
let make = () => {
  let clicks = React.useRef(0);

  <div onClick={_ => clicks.current = clicks.current + 1} />;
};

DOM elements allow you to pass refs to track specific elements that have been rendered for side-effects outside of React's control. To do this you can use the ReactDOM.Ref module.

[@react.component]
let make = () => {
  let divRef = React.useRef(Js.Nullable.null);

  React.useEffect(() => {
    doSomething(divRef);
  });

  <div ref={ReactDOM.Ref.domRef(divRef)} />;
};

For some cases it's easier to work with callback refs which get called when the DOM node changes. We support this use-case as well using ReactDOM.Ref.callbackDomRef.

[@react.component]
let make = () => {
  <div ref={ReactDOM.Ref.callbackDomRef(ref =>
    doEffectWhenRefChanges(ref)
  )} />;
};
← ReactDOMTesting components →