See form the snippet below that the getInitialState
is executed on every render. Even though the value returned from it is only used during the 1st render.
I know this is normal Javascript behavior. But is there a way to avoid it using React?
function App() {
function getInitialState() {
console.log('Executing getInitialState...');
return({
foo: 'bar'
});
}
const [myState,setMyState] = React.useState(getInitialState());
const [myBoolean,setMyBoolean] = React.useState(false);
return(
<React.Fragment>
<div>I am App</div>
<div>My state: {JSON.stringify(myState)}</div>
<div>My boolean: {JSON.stringify(myBoolean)}</div>
<button onClick={()=>setMyBoolean((prevState) => !prevState)}>Force Update</button>
</React.Fragment>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
Don't call the function directly inside the useState
, pass an anonymous function to trigger the function. Refer to the official Doc.
function getInitialState() {
console.log('Executing getInitialState...');
return({
foo: 'bar'
});
}
function App() {
const [myState,setMyState] = React.useState(()=>getInitialState());
const [myBoolean,setMyBoolean] = React.useState(false);
return(
<React.Fragment>
<div>I am App</div>
<div>My state: {JSON.stringify(myState)}</div>
<div>My boolean: {JSON.stringify(myBoolean)}</div>
<button onClick={()=>setMyBoolean((prevState) => !prevState)}>Force Update</button>
</React.Fragment>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With