Code that only runs once when a React component's state updates
<p>I have a react component called index.tsx in my game project which has a variable that updates the state, assuming that the component refreshes every time the user's balance changes. </p><p>
I'm creating a "net position" function where when starting the game the user's balance is saved as a reference value and then only additions and subtractions for each transaction should be made from that reference value. </p><p>
Assuming the user has a balance of $5000 at the beginning (in the footerBalance variable), the Net Position label will show that value as 0 (in the netPositionBalance variable), with $5000 as the base. Now the user wins $100 in the next game, his balance will become $5100 (in the footerBalance variable) and the net position will become $100 (in the netPositionBalance variable). </p><p>
What happens now is that once the balance is updated, my net position amount is also updated, and since it's in the same component file, the net position becomes 0. </p><p>I hope this is fixed at the beginning and that this particular code should not re-render, no matter how the component refreshes. </p><p></p>
<p>The code block to obtain the balance is as follows:</p>
<pre class="brush:php;toolbar:false;">const footerBalance = useAppSelector(state => state.app.footerUnformattedBalance); //This will change the balance, i.e. it will give $5000 after winning $100 Afterwards, it will become $5100</pre>
<p>I need a variable called footerBalanceAtStart so that I can display the net position (in the variable netPositionBalance) from the starting point, similar to the following: </p>
<pre class="brush:php;toolbar:false;">let netPositionBalance = Number(footerBalanceAtStart) - Number(footerBalance); //During the game, it should be updated to $100</pre>
<p>I would like "footerBalanceAtStart" to be defined to only get the balance once and then remain constant for the entire duration of the project. </p>