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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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? i.gyazo.com/e4cb98346510aa684c15c4b3ebae3fca.mp4
@Shimsho how are you updating the array? Check stackoverflow.com/a/65506651 for how to do it properly
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.