Skip to content

Render issue with the state hook #74

@JulesGuesnon

Description

@JulesGuesnon

Hello !
I wrote a component like this:

let%component make = (~render, ()) => {
  let%hook (currentRoute, setCurrentRoute) =Hooks.state(Store.route^);

  let%hook () =
    Hooks.effect(
      OnMount,
      () => {
        Store.subscribe((_, newRoute) => setCurrentRoute(_ => newRoute));
        None;
      },
    );

  <View> {render(state.currentRoute)} </View>;
};

It's supposed to rerender every time the route update. It works on the first update of my route, and then the component doesn't update at all. I added some log inside the setCurrentRoute, it is triggered, but component still not rerender.

Someone suggested that I make it with a reducer and it worked perfectly:

type action =
  | Route(string);

type state = {currentRoute: string};

let reducer = (action, state) => {
  switch (action) {
  | Route(route) => {currentRoute: route}
  };
};

let%component make = (~render, ()) => {
  let%hook (state, dispatch) =
    Hooks.reducer(~initialState={currentRoute: Store.route^}, reducer);

  let%hook () =
    Hooks.effect(
      OnMount,
      () => {
        Store.subscribe((_, newRoute) => dispatch(Route(newRoute)));
        None;
      },
    );

  <View> {render(state.currentRoute)} </View>;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions