最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - useState and useRef initial values getting computed every re-render - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 9

You can pass a function to the useState hook to have your value lazily initialized.

For example:

const [state, setState] = useState(() => new SomeObject());
发布评论

评论列表(0)

  1. 暂无评论