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

There's a thing I'm late to notice:const [object, setObject] = useState(new SomeObject());Her

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());

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744675381a4587293.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信