Book Image

ReasonML Quick Start Guide

By : Raphael Rafatpanah, Bruno Joseph D'mello
Book Image

ReasonML Quick Start Guide

By: Raphael Rafatpanah, Bruno Joseph D'mello

Overview of this book

ReasonML, also known as Reason, is a new syntax and toolchain for OCaml that was created by Facebook and is meant to be approachable for web developers. Although OCaml has several resources, most of them are from the perspective of systems development. This book, alternatively, explores Reason from the perspective of web development. You'll learn how to use Reason to build safer, simpler React applications and why you would want to do so. Reason supports immutability by default, which works quite well in the context of React. In learning Reason, you will also learn about its ecosystem – BuckleScript, JavaScript interoperability, and various npm workflows. We learn by building a real-world app shell, including a client-side router with page transitions, that we can customize for any Reason project. You'll learn how to leverage OCaml's excellent type system to enforce guarantees about business logic, as well as preventing runtime type errors.You'll also see how the type system can help offload concerns that we once had to keep in our heads. We'll explore using CSS-in-Reason, how to use external JSON in Reason, and how to unit-test critical business logic. By the end of the book, you'll understand why Reason is exploding in popularity and will have a solid foundation on which to continue your journey with Reason.
Table of Contents (10 chapters)

Client-side routing

ReasonReact comes with a built-in router found in the ReasonReact.Router module. It is quite unopinionated and therefore flexible. The public API has only four functions:

  • ReasonReact.Router.watchUrl: (url => unit) => watcherID
  • ReasonReact.Router.unwatchUrl: watcherID => unit
  • ReasonReact.Router.push: string => unit
  • ReasonReact.Router.dangerouslyGetInitialUrl: unit => url

The watchUrl function starts watching the URL for changes. When changed, the url => unit callback is called. The unwatchUrl function stops watching the URL.

The push function sets the URL, and the dangerouslyGetInitialUrl function gets a record of type url. The dangerouslyGetInitialUrl function is meant to be used only within the didMount lifecycle hook, alongside watchUrl, to prevent issues with stale information.

The url type is defined as follows:

type url = {
path: list...