dai-shi / use-context-selector

React useContextSelector hook in userland
https://www.npmjs.com/package/use-context-selector
MIT License
2.68k stars 61 forks source link

The component doesn't redraw, but the component function is still executed #97

Closed runenielsen closed 1 year ago

runenielsen commented 1 year ago

I have tested your minimal example, and when I insert console.log('Counter') in the Counter function and console.log('TextBox') in the TextBox function, all the sub-components log, when I click on a counter button or change a text, even if only the component type where I made the change is actually redrawn (the random number changes).

So the component functions for TextBox are still executed, when I update the Counter and vice versa, even if the result for some reason isn't used by React to actually redraw the Textbox components.

I assume this isn't the intention...?

dai-shi commented 1 year ago

Can you put console.log in useEffect and see how it goes? If the result is somewhat expected, it's intentional behavior.

runenielsen commented 1 year ago

When I put console.log in useEffect, it works as I would expect (only the component I change logs anything). I'm not sure I understand, why this is intentional though. I would definitely prefer the unrelated components to not be called at all, not sort of a halfway render :-)

dai-shi commented 1 year ago

It's required to avoid so called stale props issue. You don't want some mismatch between props and context value. If it's not the issue for your case, what you want should be possible.

runenielsen commented 1 year ago

Ok, thanks.

willdspd commented 1 year ago

Seconding this. I just spent quite a long time trying to figure out why my components were re-rendering when using this library because I was using console.log. In my opinion, if possible, the default functionality should 100% be to not call unrelated components. For one, it's confusing when testing the lib, two, because it feels less clean somehow. @dai-shi Fantastic library aside from this. Thank you for all your work in the react state space!

dai-shi commented 1 year ago

If we give up concurrent rendering support, it's possible. But, that's the whole motivation of developing this library. https://github.com/dai-shi/will-this-react-global-state-work-in-concurrent-rendering

Without such capability, it's pretty easier to implement an alternative library.

FYI, the unexpected behavior is just how useReducer works. https://twitter.com/dai_shi/status/1534170089981100032

willdspd commented 1 year ago

I haven't played around much with concurrent mode so will reserve an opinion on this. It's a tiny issue with an overall fantastic library, so again, thank you!

dai-shi commented 1 year ago

~fwiw, if you have a stable selector, the behavior might be improved. https://github.com/dai-shi/use-context-selector/issues/100#issuecomment-1407535061~

Closing as answered.