DEV Community

Rickard Natt och Dag
Rickard Natt och Dag

Posted on • Originally published at willcodefor.beer on

ReScript: Using useState in rescript-react

React has a useState hook that's great for keeping track of some simple state. rescript-react also has this hook, but the API is a bit different in that it only contains the function variations of useState. Here's a basic example that extends the example we created previously.

@react.component
let make = () => {
  let (displayValue, setDisplayValue) = React.useState(() => false)

  <div>
    {displayValue ? React.string("The best value") : React.null}
    <Button onClick={_ => setDisplayValue(displayValue => !displayValue)}>
      {React.string("Toggle value")}
    </Button>
  </div>
}
Enter fullscreen mode Exit fullscreen mode

React.useState takes a function where the return value is our initial state. In return, we get a tuple of the current state and a setter. The types for the return values are inferred from the initial state. In this case the types are bool for displayValue and (bool => bool) => unit for setDisplayValue.

We could then use the value, defined as displayValue in our example, to conditionally display a text. Both sides of the ternary need to have the same type so we use React.null, which maps to React.element like React.stringdoes, when we don't want to display anything.

To update the value we call the setter function, defined as setDisplayValue in our example. In this case, we toggle the displayValue based on the previous value.

The bindings for useState to the React implementation acknowledges that the API isn't the best, but the only way to implement the state with type safety. The recommendation is to use useReducer whenever possible.

Top comments (0)