search-ui: Cannot use hooks because of how containers call their views
The following:
const MyResultView = () => {
const someHook = useHook();
return <div>My Result</div>;
};
<Result view={MyResultView} />
Errors with: https://reactjs.org/warnings/invalid-hook-call-warning.html
I think this is because of how containers call their views:
When I change that to:
return <View
className={className},
result={result}
key={`result-${result.id.raw}`}
onClickLink={() => this.handleClickLink(result.id.raw)}
titleField={titleField}
urlField={urlField}
/>;
Everything works fine.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 6
- Comments: 16 (12 by maintainers)
Commits related to this issue
- Merge branch 'master' into #276-react-hooks-fix — committed to joemcelroy/search-ui by joemcelroy 2 years ago
- Merge branch '#276-react-hooks-fix' of github.com:joemcelroy/search-ui into #276-react-hooks-fix — committed to joemcelroy/search-ui by joemcelroy 2 years ago
- #276 react hooks fix for custom view components (#603) * bump to allow node version 14.17 or above * add vscode debug configurations for views package * change to way View components are mounte... — committed to elastic/search-ui by joemcelroy 2 years ago
Jason, re “I’m hesitant to make the switch from View() to <View /> because I don’t fully understand the functional differences between the two styles.” … the difference is that one is seriously non-idiomatic to React and bypasses React’s internals completely. If you simply call a function you never trigger the tracking that allows React to register and call hooks properly. What’s worse, in certain cases that may not trigger an error, you may actually end up registering the hooks on the wrong component! Bottom line: a function only becomes a component to the React core when you actually render it --as is evidenced by the workaround above, so render it!
https://kentcdodds.com/blog/dont-call-a-react-function-component
Please fix this. It wouldn’t be a minor issue for any React framework
(Elastic is great. Keep up the good work)
For others who run into this, you can workaround via:
this change has now been released under v1.9.0 😄 LMK of any issues.