0

Sometimes, we only need to use the accessor/mutator of a shared state (e.g: setBlockPickerMenu).

const [blockPickerMenu, setBlockPickerMenu] = useRecoilState(blockPickerMenuState);
...
setBlockPickerMenu(null)

And we don't need the value itself (e.g: blockPickerMenu).

What happens inside React when we're doing the above? Does the component subscribes to changes to blockPickerMenu even though we don't actively use it? Does it perform needless re-renders upon changes? Is there a way to optimize things somehow?

The above example uses Recoil, but I assumed it'd work similarly for any shared state (Redux, etc.)

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
  • 1
    I tried to summarize all your 5 questions, if it isn't enough please focus on a single question in a separate thread and tag me. – Dennis Vash Feb 10 '21 at 16:46

1 Answers1

3

useRecoilState calls useRecoilValue which will implicitly subscribe the component to the given state.

function useRecoilState(recoilState) {
  // ...
  return [useRecoilValue(recoilState), useSetRecoilState(recoilState)];
}

So yes, it subscribed even if the state isn't used when only needing the setter.

If you want to only be subscribed to the setter, call useSetRecoilState(state).

I assumed it'd work similarly for any shared state (Redux, etc.)

You can't assume, every library and its implementation, for example in Redux, you can't have such a use case since setter and state are decoupled via useDispatch and useSelector.

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • Thanks for your input. `So yes, it subscribed even if the state isn't used when only needing the setter.` => It might still subscribe but ignore updates if the value isn't used? I'm not quite sure about how React deals with that, can it affect performances? The goal of my question is to know whether I should optimize it, and thus convert `useRecoilState` to `useRecoilValue` when I know the getter won't be used. – Vadorequest Feb 11 '21 at 00:09
  • 1
    React does not detect if a value is used – Dennis Vash Feb 11 '21 at 04:33
  • Okay, so I better make sure to use the `useSetRecoilState` when not needing to subscribe and it'll improve performances. Thanks! – Vadorequest Feb 11 '21 at 10:19