Create a Button in React that Changes Local State and Automatically Updates the UI

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

After creating some state with useState, we can call the set function to update the data in local state, which will automatically "re-render" the component, and update the UI.

To do that, we'll first create a new function that will update the state that we want:

const updateCount = () => {
  setCount(count + 1)
}

and then we can pass that updateCount function into the onClick of a button:

<button onClick={updateCount}>Click Me!</button>

which will then call updateCount once clicked, which will call setCount, which will update the count state, and automatically display that update on the UI.

Chris Achard: [0:00] To update this count state, we're going to call setCount with some new value. Let's make a button to do that. The button can say Click Me. As an attribute to the button we're going to say onClick. Notice how onClick is camel cased, not like the HTML onclick. Inside of there, we're going to put curly braces because we want a JavaScript reference to a function that we're going to write.

[0:25] Let's write that function first. We can say updateCount, and that will be a regular function. Inside of that, we can say setCount, so we're going to call the updater function with count + 1. It's going to take whatever the value of count is and set it to that plus one.

[0:43] In the onClick attribute down here, we can just pass the updateCount function, and then, on a click of button, it will call updateCount which will set the count to the count + 1. Save that and see if it works.

[0:55] It starts at 5, because we have the default set at 5. If we change that back to , then it starts at and we can click up on Hello, React! And click up on Hello, Chris!

[1:06] Notice how the state here is different and independent than the state here. Each component has its own internal state.

egghead
egghead
~ 2 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today