coolsoftwaretyler / react-compiler-demo-with-mobx-state-tree

MobX-State-Tree Reactivity working with React Compiler
0 stars 0 forks source link

Potential rules of hooks violation #2

Open josephsavona opened 4 days ago

josephsavona commented 4 days ago

This is exciting! I just wanted to check my understanding. From the implementation at https://github.com/coolsoftwaretyler/react-compiler-demo-with-mobx-state-tree/blob/8d9d6226ecd4c67dc2a630794d1d6126e41e6955/hooks/useObservable.ts#L45, it looks like this allows calling hooks dynamically? Basically any object access could under the hood be a hook call, and there's no linter to guard that those property accesses are unconditional. So it isn't clear to me how this makes Mobx State Tree compatible. Did I miss something?

coolsoftwaretyler commented 4 days ago

Thanks @josephsavona! Good call. I can probably refactor this conditional hook somehow and get the condition out of there by making the useObservableProperty hook a little more resilient to other types of values.

Linter

I just realized I broke my linter config, so I fixed it and I do see the error you bring up:

  30:12  error  React Hook "useObservable" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?                                                         react-hooks/rules-of-hooks
  45:16  error  React Hook "useObservableProperty" is called in function "get" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use"  react-hooks/rules-of-hooks

Again, I should be able to fix that with some refactoring.

Compatibility

As far as compatibility, I see the React Compiler working, based on the documented steps for validation. If you spin up the Remix app and go to http://localhost:5173/hook, you'll see this (notice HookPage has the "memo" tag with stars/highlight):

compiler-working

Compared to the observer page at http://localhost:5173/observer, which shows this (the memo tag is not highlighted, does not have the little stars):

compiler-not-working
coolsoftwaretyler commented 4 days ago

Linter is much happier with this: https://github.com/coolsoftwaretyler/react-compiler-demo-with-mobx-state-tree/pull/3. React compiler is still giving me the memo tags.

I'll still need to figure out how to get the value back from lazily evaluated views, which are functions and need to be evaluated as such.

Thanks for taking a look at this! Exactly the kind of feedback I've been looking for, and it's great you caught my misconfiguration haha.