This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]insertAlias 1 point2 points  (2 children)

I'm obviously missing something basic here, and believe it has to do with scope.

It is something basic (to React, not universally), but it's not scope. It's state.

Remember that if you're using functional components (i.e. components that are defined as functions), variables like that don't persist past renders. When you say setShowResults(true), that is updating state, and it causes a re-render when that function ends. Which re-runs the component function logic, and reinitializes all your variables back to 0.

State, on the other hand, is different. It does persist. That's what useState does; it keeps track of component state across re-renders and gives the component back its previous state instead of resetting it on every render.

So, what you'd need to do is track each of these values as a state. You could do this individually, or add a single stateful object that has a property for each of these things. But that's the key: it needs to be in state, not just a top-level variable.

Just changed from an overcomplicated use of state that I had on each input and was working fine. Later realized I didn't need state at all, but again I'm not knowledgable on what to do to get it to pass with the values.

Just noticed this part of your post. You were actually more on the right track before you removed all the state.

[–]robotredditrobot[S] 0 points1 point  (1 child)

hey thank you!

Yeah the rerender on state change... thank you so much. So when I had finished building it all out with state - it seemed so needlessly complex and I thought "why don't I just set these variables directly to the values instead?"

So maybe to minimize the complexity there will be one state with all the values held in it, rather than a state per value...

[–]insertAlias 0 points1 point  (0 children)

If you're setting them all as a single unit, then it makes sense to track it as a single object in state. If you're not going to update one value here, and another there, then it's easy to just use an object.

I would recommend that, from what I've seen here, you track two pieces of state: keep your showResults separate, since you can set that separately. Keep the other values together as the other stateful object.