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