DEV Community

Rickard Natt och Dag
Rickard Natt och Dag

Posted on • Originally published at willcodefor.beer on

6

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more