1

Is it still possible to render variables in react? Trying to use a more lightweight method of storing data on a component, but variables don't seem to render anymore in react. Is useRef the new method for variables or is it still possible in basic let variables.

Here is an example of variables not rendering in react: https://codesandbox.io/s/serene-galileo-ml3f0?fontsize=14

Shimsho
  • 107
  • 9

2 Answers2

2

You have a misconception about how React handles state. The reason why normal variables don't seem to work in React is actually an optimization. React only rerenders the elements on your page when absolutely necessary. The way you tell React "hey, my state changed, can you update the page to reflect that" is by using state variables. In your example, React only rerenders the elements that reference the b variable when you update it using setB. However, it does not rerender the elements that represent a when you update it using a++, because it has no way to detect that a was updated.

useState is actually more efficient than local variables, because it rerenders only what is necessary.

virchau13
  • 1,175
  • 7
  • 19
  • At the moment I'm having problems with useState with an Array that consecutively updates every 2 seconds, the function is supposed to add to the array but seemingly loads the previous state and bugs a bit. Is there any method to fix this? https://i.gyazo.com/e4cb98346510aa684c15c4b3ebae3fca.mp4 – Shimsho Oct 28 '21 at 02:59
  • @Shimsho how are you updating the array? Check https://stackoverflow.com/a/65506651/ for how to do it properly – virchau13 Oct 28 '21 at 03:03
0

see virchau13's answer.

Although saving to a state is more intensive than a simple variable assignment, you have to take into account that what you see on the screen will only change via renders. So if you wanted to see the display increment on the screen, it will only do so via renders, which is most easily achieved through state changes.

Derek Kim
  • 190
  • 2
  • 11