about summary refs log tree commit diff
path: root/website/sandbox/nut-score/src/ReducerFromReactJSDocs/ReducerFromReactJSDocs.re
blob: ddc5f0994649d0f28e244a343a842ac63f24da12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// This is the ReactJS documentation's useReducer example, directly ported over
// https://reactjs.org/docs/hooks-reference.html#usereducer

// Record and variant need explicit declarations.
type state = {count: int};

type action =
  | Increment
  | Decrement;

let initialState = {count: 0};

let reducer = (state, action) => {
  switch (action) {
  | Increment => {count: state.count + 1}
  | Decrement => {count: state.count - 1}
  };
};

[@react.component]
let make = () => {
  let (state, dispatch) = React.useReducer(reducer, initialState);

  // We can use a fragment here, but we don't, because we want to style the counter
  <div>
    <div>
      {React.string("Count: ")}
      {React.string(string_of_int(state.count))}
    </div>
    <div>
      <button onClick={_event => dispatch(Decrement)}>
        {React.string("-")}
      </button>
      <button onClick={_event => dispatch(Increment)}>
        {React.string("+")}
      </button>
    </div>
  </div>;
};