Recoil: Update multiple separate atoms in a single render

Created on 3 Jun 2020  路  4Comments  路  Source: facebookexperimental/Recoil

Hi,

is there any way to enforce the update of two separate atoms within a single react render?

I don't have any problem and/or use case related to this at the moment, I'm just curious.

Have a nice day 馃檪

duplicate

Most helpful comment

Can use the selector to update multiple atoms at the same time.

something like below

const HsvState = selector({
  key: "hsv",
  get: ({ get }) => {
    const h = get(HState);
    const s = get(SState);
    const v = get(VState);
    return [h, s, v];
  },
  set: ({ get, set }, [h, s, v]) => {
    if (h == null) {
      h = get(HState);
    }
    const { r, g, b } = HSVtoRGB(h, s, v);
    set(HState, h);
    set(SState, s);
    set(VState, v);
    set(RState, r);
    set(GState, g);
    set(BState, b);
  }
});

You can visit https://codesandbox.io/s/recoil-color-picker-nh1gw to see more details.

I hope this helped you.

All 4 comments

Can use the selector to update multiple atoms at the same time.

something like below

const HsvState = selector({
  key: "hsv",
  get: ({ get }) => {
    const h = get(HState);
    const s = get(SState);
    const v = get(VState);
    return [h, s, v];
  },
  set: ({ get, set }, [h, s, v]) => {
    if (h == null) {
      h = get(HState);
    }
    const { r, g, b } = HSVtoRGB(h, s, v);
    set(HState, h);
    set(SState, s);
    set(VState, v);
    set(RState, r);
    set(GState, g);
    set(BState, b);
  }
});

You can visit https://codesandbox.io/s/recoil-color-picker-nh1gw to see more details.

I hope this helped you.

Nice, trying with only 2 atoms it didn't look like it, thanks for your prompt reply.

I simplified a fork of that sandbox just to inspect the number of renders:

https://codesandbox.io/s/recoil-multiple-set-state-1-render-lby2l?file=/src/App.js

I'm getting a bit more renders than I was expecting (4 at the beginning and 2 instead of 1 on set) but it looks like the effort is to make my use case possible.

I'm guessing the unexpected renders might disappear over time? (or am I doing/expecting something wrong?)

This is because you are development in the strict mode, for more details please see: https://github.com/facebookexperimental/Recoil/issues/75

Duplicate of #75

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robsoncezario picture robsoncezario  路  3Comments

adrianbw picture adrianbw  路  3Comments

yuantongkang picture yuantongkang  路  3Comments

ibnumusyaffa picture ibnumusyaffa  路  4Comments

jamiewinder picture jamiewinder  路  3Comments