20-Dec

Functional

You should write React in F#

6 min read

·

By Bjørn-Ivar Strøm

·

December 20, 2022

React.js is a powerful and popular JavaScript library that allows developers to create rich, interactive user interfaces. In recent years, React has become the go-to technology for creating web and mobile applications. But what if you could take your React development to the next level by writing your React code in F#?

In this article, we’ll explore the advantages of writing React in F#, and explain why making the switch could be a great way to take your React development to the next level.

TypeScript

Even if you can write React in JavaScript, TypeScript has become very popular. It basically allows you to write JavaScript with types. Furthermore TypeScript is a superset of JavaScript, which makes it easy to get started with if you already know JavaScript.

Using TypeScript will remove some issues that can arise when using JavaScript alone. It makes code easier to maintain and reason about. Honestly: if your team consists of more than one person, or if you are paid to write code, using JavaScript for anything substantial is irresponsible and a waste of your client’s money.

F#

While TypeScript has a strong type system, it does have one major drawback. It is a superset of JavaScript. It needs to be able to type everything you can express in JavaScript. This means that you have a type system that lets you get away with doing too much crazy stuff.

TypeScript's type system allows developers to make assumptions about the types of data they are working with. This can lead to errors and bugs if the assumptions are wrong. Additionally, the type system is more relaxed than other languages, so it can be easy to overlook a potential problem. For example, TypeScript will not prevent you from passing the wrong type of data to a function, which can lead to unexpected behaviour. It is important for developers to understand the types of data they are working with and to be careful when making assumptions about them.

F# on the other hand has a much stricter compiler and rules. While the syntax might be reminiscent of a TypeScript and Python mix, it is far more similar to Elm than it is to TypeScript.

In F# everything is immutable by default, in TypeScript you would need some third-party library to achieve this. It also has a much better standard library. In F#, you can simply call the groupBy function when you need it, without having to worry about whether your favourite utility library is up to date. Lastly F# has pipelines, which is such an enjoyable way to compose functions.

React

A very simple react component could look like this:

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}

It is normally written in JavaScript or TypeScript - which is compiled to JavaScript.

You can also write React in F# with a library called Feliz and compile it to JavaScript with a tool called Fable.

Fable + Feliz
In order to interact with the DOM and call React, Feliz is used as the library of choice.
To make this all work, F# is compiled to JavaScript with Fable. The result should then be used in combination with a bundler for further optimization.

In the future, Fable will also enable you to use JSX directly in your F# code, making it easier to work with existing React components and lower the barrier to entry.

Components in F# and TypeScript

The same example above in TypeScript

type Props = {
    name: string
}
function Welcome({name}: Props) {
    return <h1>Hello, {name}</h1>;
}

And in F#

[<ReactComponent>]
let Welcome name =
    Html.h1 $"{Hello}, name"

The main differences here are:

In F# you do not need to specify types, the compiler will infer them. However you can specify them if you want.

In F#, HTML markup is not written in JSX, but rather consists of normal F# functions. These functions are typed so you can easily see what the different components do and what parameters they take. This means that your HTML markup is now type safe. If you mess it up it won’t compile, and that is lovely!

Hooks F# and TypeScript

You can use hooks just as you would expect:

Typescript:

function Counter() {
    const [count, setCount] = useState(0);
    return (
    <div>
        <button onClick={() => setCount(count+1)}>+</button>
        <button onClick={() => setCount(count-1)}>-</button>
        <h1>{count}</h1>
    </div>
);

F#:

[<ReactComponent>]
let Counter() =
    let (count, setCount) = React.useState(0)
    Html.div [
        Html.button [
            prop.onClick (fun _ -> setCount(count + 1))
            prop.text "+"
        ]
        Html.button [
            prop.onClick (fun _ -> setCount(count - 1))
            prop.text "-"
        ]

        Html.h1 count
    ]


Community
Lasty I would like to quickly mention the F# community. It is a highly supportive environment that encourages collaboration and learning. The F# language is designed to be easy to learn and use, and the community is full of welcoming and helpful people who are always willing to help out newbies.

They also do a lot of work for the community. Making tools and libraries which are super useful.

I recommend checking out the F# website for more info on the slack and discord channel.

Conclusion
React.js is a popular JavaScript library that allows developers to create rich, interactive user interfaces.
In recent years, React has become the go-to technology for creating web and mobile applications.

However, using TypeScript or JavaScript to write React code can have its limitations.
One alternative is to use F#, a programming language that has a stricter compiler, immutable values by default, a better standard library, and function pipelines.

F# can be used to write React code with the help of tools such as Feliz and Fable,
which enable developers to compile F# code to JavaScript.
Using F# for React development has several benefits
including improved type safety, more concise and maintainable code,
and the ability to take advantage of F#'s powerful language features.

While using F# for React development requires the use of additional tools and libraries,
the benefits outlined in the article could make it worthwhile for those looking to take their React development to the next level.

Here are some links you can check out if this is interesting:

- FSharp.org - the F# website

- F# for fun and profit - THE website to learn F#

- Fable - Compiling F# to other languages like JavaScript

- Feliz - the library that enables React.

- Elmish book - Practical and free e-book on how to write "Elm"-ish code with F#.

- Preact - How to on using Preact instead of React if you prefer that.

- Sutil - if you prefer something Svelte inspired.

- Lit - For the developer who wants to write HTML