Defining the function component

Now, we define the same component as a function component:

  1. First, we remove all code from the src/App.js file.
  2. Next, in src/App.js, we import React, and the useState Hook:
    import React, { useState } from 'react'
  1. We start with the function definition. In our case, we do not pass any arguments, because our component does not have any props:
    function MyName () {

The next step would be to get the name variable from the component state. However, we cannot use this.state in function components. We have already learned that Hooks are just JavaScript functions, but what does that really mean? It means that we can simply use Hooks from function components, just like any other JavaScript function!

To use state via Hooks, we call useState() with our initial state as the argument. This function returns an array with two elements:

    • The current state
    • A setter function to set the state
  1. We can use destructuring to store these two elements in separate variables, as follows:
            const [ name, setName ] = useState('')

The previous code is equivalent to the following:

            const nameHook = useState('')
const name = nameHook[0]
const setName = nameHook[1]
  1. Now, we define the input handler function, where we make use of the setName setter function:
            function handleChange (evt) {
setName(evt.target.value)
}
As we are not dealing with classes now, there is no need to rebind this anymore!
  1. Finally, we render our user interface by returning it from the function. Then, we export the function component:
    return (
<div>
<h1>My name is: {name}</h1>
<input type="text" value={name} onChange={handleChange} />
</div>
)
}

export default MyName

And that's it—we have successfully used Hooks for the first time! As you can see, the useState Hook is a drop-in replacement for this.state and this.setState.

Let's run our app by executing npm start, and opening http://localhost:3000 in our browser:

Our first React app with Hooks

After implementing the same app with a class component and a function component, let's compare the solutions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.150.163