Hello,
As a bit of an exercise I’d like to make a YouTube video on how React components in ReScript work.
I’m not sure if I’m actually going to do it, but content creation does interest me from time to time.
Anyway, this is what I have in mind to cover. Would be great to hear some thoughts on this list.
Did I miss anything?
Getting Started with ReScript
- Run the command:
bun create rescript-app@next - Use v12 alpha
- Inspect the
rescript.jsonfile:- Set
jsxto version 4 - Include
@rescript/react
- Set
- Start the ReScript watcher with:
bunx rescript -w - Run the development server with:
bun run dev
Define a React Component
- You need a function called
makethat takes a props record as a single property. - The
makefunction allows JSX syntax to work for that module. -
<Foo />is shorthand for invoking theFoo.makefunction. - You can spread
...ReactDOM.domPropsto allow optional existing well-known properties. - You can create an instance of that element in another module (use
<Foo />inApp.res). - Every file in ReScript is a module, which means you cannot reuse a file name.
- Each module can have only one
makefunction, but you can have nested modules. - The name of the component is determined by the module name.
- Each React component must return the
React.elementtype. - You can compose other elements and primitive types.
- You cannot use raw text in JSX as the type wouldn’t match.
- Convert primitives like strings using
->React.string.
@react.component Attribute
- You can use labeled arguments to define your props; in this case, annotate your function with
@react.component. - Use
unitwhen you have no props. -
@react.componenttransforms your source code and creates a prop type behind the scenes. - Due to this transformation, you must use
unitor all labeled arguments; otherwise, the compiler will complain. - It also transforms the
makefunction to an uppercased function with the module name.
@react.componentWithProps Attribute
- Use this when you want to define a record type yourself but still want the transformation of
maketo uppercase module name function. - It is recommended to always use this attribute for better compatibility with the wider React ecosystem.
Fast Refresh
- Inspect the change in the
react()plugin invite.config.js. - Everything is public in ReScript by default.
- For fast refresh to work in Vite, only components can be exported.
- We use signature files to achieve this.
ESLint & React Compiler
- Writing ReScript code does not guarantee adherence to React’s rules.
- Linting the output JavaScript code can be helpful.
- Set up for linting and the React compiler should be shown.
- Add
@directive("'use memo'")to make it work.