Skip to content

benadamstyles/reason-pure-component

Repository files navigation

reason-pure-component

A PureComponent implementation for ReasonReact. Simplify your shouldUpdate!

Installation

npm install reason-pure-component

bsconfig.json:

"bs-dependencies": [
  "reason-react",
+  "reason-pure-component"
]

Usage

Using reason-pure-component doesn't result in fewer lines of code, necessarily. The benefit is in the abstraction of how you compare oldSelf.retainedProps and newSelf.retainedProps. You simply define an equality function – in this case == . Thanks to the OCaml type system, if you forget to define any of the required configuration, the program will not compile – whereas if you use ReasonReact.statelessComponentWithRetainedProps directly, and forget to define shouldUpdate, no one is any the wiser.

+ module Config = {
    type retainedProps = {
      view: string,
      subview: option(string),
    };
+   let name = "Breadcrumb";
+   let equals = (==);
+ };

- let component =
-    ReasonReact.statelessComponentWithRetainedProps(
-      "Breadcrumb"
-    );

+ module Pure = PureComponent.Stateless(Config);

let make = (~view, ~subview=?, _children) => {
-  ...component,
+  ...Pure.component,

-  retainedProps: {view, subview},
+  retainedProps: Config.{view, subview},

-  shouldUpdate: (oldAndNewSelf) =>
-    oldAndNewSelf.oldSelf.retainedProps !=
-    oldAndNewSelf.newSelf.retainedProps,

  render: _ =>
    <div>
      <p>{ReasonReact.string(view)}</p>
      <p>
        {ReasonReact.string(
          subview->Belt.Option.getWithDefault("")
        )}
      </p>
    </div>,
};

Known issues

genType compatibility

genType assumes your component exports its component record. Therefore, in the above example, you need to add the following line:

let component = Pure.component;