admin管理员组文章数量:1391934
There's a thing I'm late to notice:
const [object, setObject] = useState(new SomeObject());
Here, we construct an instance of SomeObject
on every single re-render.
Then, if it's the ponent's initial render, it gets returned to object
, otherwise it's just discarded.
Whatever is passed in as the initial argument is evaluated and discarded over and over again. It also better be pure, since re-renders can happen in arbitrary intervals and in arbitrary amounts. Given that constructing some objects or large arrays can be quite expensive, isn't it a bit suboptimal?
What's the solution here? Am I misunderstanding something, or such an elementary feature in React is implemented in such an suboptimal way?
There's a thing I'm late to notice:
const [object, setObject] = useState(new SomeObject());
Here, we construct an instance of SomeObject
on every single re-render.
Then, if it's the ponent's initial render, it gets returned to object
, otherwise it's just discarded.
Whatever is passed in as the initial argument is evaluated and discarded over and over again. It also better be pure, since re-renders can happen in arbitrary intervals and in arbitrary amounts. Given that constructing some objects or large arrays can be quite expensive, isn't it a bit suboptimal?
What's the solution here? Am I misunderstanding something, or such an elementary feature in React is implemented in such an suboptimal way?
Share Improve this question edited Oct 17, 2019 at 13:52 John Smith asked Oct 17, 2019 at 13:47 John SmithJohn Smith 4,4136 gold badges28 silver badges49 bronze badges1 Answer
Reset to default 9You can pass a function to the useState
hook to have your value lazily initialized.
For example:
const [state, setState] = useState(() => new SomeObject());
本文标签: javascriptuseState and useRef initial values getting computed every rerenderStack Overflow
版权声明:本文标题:javascript - useState and useRef initial values getting computed every re-render - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744675381a2619076.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论