When would we use "useImperativeHandle" in ReactJs' hooks?
还没有人认领这个 Issue。
- 主要语言
- JavaScript
- 星标
- 11.8k
- 派生
- 7.9k
- 平均合并
- 1 天 11 小时
- 30 天内合并 PR
- 11
描述
I am trying to understand what ReactJs' team expects from developers when using the useImperativeHandle's method. Currently the documentation indicates that:
imperative code using refs should be avoided in most cases.
useImperativeHandleshould be used with forwardRef.
Does this means it is good practice to useuseImperativeHandlewithforwardRef? When would we useuseImperativeHandletypically?
More specifically, in this discussion on stackoverflow about how calling child'smethodsfrom parents , someone provided this answer which propose to useuseImperativeHandle. Then some comments argued that this is not good practice:
This is not really a good pattern. {...} It's better to pass
propsinto the child component and then have a button click in the parent change the parent'sstate, and pass astateitem into the child which will trigger the child'scomponentWillReceiveProps, and use that as a trigger.
No, it's not usually the best pattern, it's more of an escape hatch when you need it, and should be used only in emergencies.{...}
I would we make the things limpid for everyone, so here my specifics questions:
-
Is it good practice to use
useImperativeHandlewithforwardRef? -
When would we use
useImperativeHandletypically? -
Can we, or not, safely use
useImperativeHandlefor the convenience of easily communicatepropertiesandmethodsto the childs' parents? -
Why the documentation say that imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef.?
-
What are the information to know to make an educated decision about the usage of
useImperativeHandle? -
lastly, is it safer, safe, and even a good practice to use the
useEffect's method to communicate element to parents, like in the following demo, here a relevant's snippet:
useEffect(() => {
ref.current = { componentState }; // get a forwardRef's reference, then transmit some state to parent by modifying the reference
validateChildren(ref.current.componentState.two);
});
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
未指定 repository 文件或测试。首先查看 useImperativeHandle 和 forwardRef 文档、链接的 Stack Overflow 讨论以及 StackBlitz 示例,以确定预期的指导内容。完成意味着通过关于适当用法和替代方案的清晰、准确的文档解决所列问题。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, react
- 领域
- documentation
- Issue 类型
- 文档
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 25/100