ReasonML ReasonReact updated with React hooks

With the latest ReasonReact update, finally support hooks, and new way of writing reasonReact with more functional approach is so much better, easier and fun.

Lets try to begin with a new Component, Button.re,

BTW, there are some API was replaced to new name space “React” from “ReasonReact”

As you can see above code, it was so much easier to write comparing to what we used to, declaring a statelessComponent or reducerComponent as example below.

Although record component are still supported in current version, they will be deprecated in anytime, one of the reason of writing ReasonReact with hook is that the component that compiles to React javascript are much clearer towards React itself. Take a look at the screenshot of record component that compiles. You can see that it included bunch of unnecessary code, such as didMount etc…

and now take a look at new functional way of ReasonReact compiles

Its like almost exactly how we would write React in javascript, in this case which means we can use the React docs and follow through the tutorial and still understand how we can implement in ReasonReact because they are identical.

So now comes the questions of how we can use React hook in ReasonReact?

Let’s start with a basic React hook API, useState. we are create a button that increase a count every time when we pressed button.

The code itself is quite easy to understand, first I create a useState of count with 0 as initialState, and useState will return a tuple of first the state, and second the setState function which I called it setCount. So during button onClick I can use the setCount method which increase the count by 1.

Let’s say you have bunch of states and actions to dispatch, we can use useReducer method.

Even we are using reducer its still easy to read. First we create a state type and create a initialState with count: 0 and we create a action type which we want to dispatch later.

then we create a React.useReducer which takes a reducer and initialState. Since we already have initialState we can just put in as second parameter, the first parameter reducer is the switch action that we we can dispatch which returns the new state, as what we did below the action type, when action is AddCount, we add 1 to count and return the new state.

Since useReducer provides tuple of state and dispatch action which is different from what useState provided (state, useState). We can make use of dispatch to dispatch a action when we trigger an event as what we did in button, onClick and dispatch(AddCount).

I will discuss other hooks somewhere, for now I hope you enjoy what you have learned and using ReasonReact hook is so much fun for me and hopefully for you too.