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

Chris Achard
InstructorChris Achard

Share this video with your friends

Send Tweet
Published a year ago
Updated 3 weeks 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.