Home > Blockchain >  Using variables instead of state
Using variables instead of state

Time:10-28

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related