Reputation: 89
I've initialize a react app using npx create-react-app
:
import React from 'react';
class Expensive {
constructor() {
console.log('constructing expensive class');
}
}
function App() {
const expensiveRef = React.useRef(new Expensive());
return (
<div className="App">
app
</div>
);
}
export default App;
However, I am seeing that constructing expensive class
is printed to the console twice. Why is this?
I get the same result if I replace
const expensiveRef = React.useRef(new Expensive());
with
const [expensiveState, setExpensiveState] = React.useState(new Expensive());
Upvotes: 2
Views: 1513
Reputation: 519
Every code is executed on every render that's why it is logged multiple times, even useState will remember the first instance.
If you want it to be initialized only once, use that useState version like this
const [expensiveState, setExpensiveState] = React.useState(() => new Expensive());
So you pass function instead of object initialization
see https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
Upvotes: 2