Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Handle an Input with React useState Hook

    Gosha ArinichGosha Arinich

    Learn to use one of the built-in React hooks, useState, to make a single controlled input work.

    We'll do this by creating a name state variable, and a handleNameChange function to update that state variable.

    Note: you need to be using a version of React that supports Hooks (versions 16.8.0 and higher)



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: We will start by creating a name variable that will hold the current value of the input. We'll go ahead and create the new input, give it a value of name. We're also supposed to give it an onChange prop, which will be a function that gets the new user input, and is supposed to update the name variable somehow.

    We'll do onChange equals handleNameChange, create a new variable called handleNameChange. It will be a function that accepts an event. We can get the value of whatever user typed using

    We're then supposed to use newValue to somehow update the name variable, but we cannot do just name equals newValue, but React will not know that something changed. Instead, we will convert name to a state variable using React hook called useState.

    const name, set name from React useState. We'll give it a default value of Joe. Now, we can call setName(newValue) in the handleNameChange function. If we type something into the input, we can see that its value is updating.

    We can also just use the name variable somewhere in render outside the input, just to make sure that they are both in sync.