React Hooks is a shiny new proposal that optimizes 90% of React code. According to Dan Abramov, Hooks are the future of React.
That sounds good, but what are Hooks, and how will they help me write better code? I’m glad you asked.
Hooks allow you to access state and lifecycle methods in function components. If the preceding sentence is unfamiliar to you, you should update your memory about React here.
The React team says it will help you write clean code with no stateful component baggage. After implementing a quasi-system form using Hooks, I agreed with them.
Let’s start by writing a simple form in a stateful component. We will rewrite the form using Hooks and you can decide which one you prefer.
Set up the
Go to codesandbox.io, create an account, log in, and create a new Sandbox. Select React when creating the sandbox.
Now that sandbox is open, we must make sure we use the React version that supports Hooks. Because Hooks are now in the public stable version of React V16.8.
Check the file editor on the left of the sandbox and then:
-
Click on ‘Dependencies’
-
Check to see if the versions of ‘React’ and ‘react-dom’ are lower than 16.8, or click Update to the latest version
Now that we’re done setting up, it’s time to write some code. Skip to the sandbox you created, create a new file called form.jsx, and paste the following code:
import React, { Component } from "react";
class Form extends Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
lastName: "",
email: "",
password: "",
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
const { firstName, lastName, email, password } = this.state;
return (
<form>
<input
value={firstName}
onChange={this.handleInputChange}
placeholder="First name"
type="text"
name="firstName"
required
/>
<input
value={lastName}
onChange={this.handleInputChange}
placeholder="Last name"
type="text"
name="lastName"
required
/>
<input
value={email}
onChange={this.handleInputChange}
placeholder="Email address"
type="email"
name="email"
required
/>
<input
value={password}
onChange={this.handleInputChange}
placeholder="Password"
type="password"
name="password"
required
/>
<button type="submit">Submit</button>
</form>
);
}
}
export default Form;
Copy the code
Now open index.js and replace the contents with the following code:
import React from "react";
import ReactDOM from "react-dom";
import Form from "./Form.jsx";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>A Simple Form in React</h1>
<Form />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Copy the code
Test the form to see if everything works. This is the “old school” way of implementing controlled forms in React.
Note the number of boilerplate files required to set the state and the way to update the state each time you enter a change.
Let’s use React Hooks. Write the same Form, but first, remove all the code in form.jsx and let’s start over.
Start by adding the following line at the top of the file:
import React, { useState } from 'react';
Copy the code
So an unfamiliar method called useState has been introduced. What is it and how do we use it?
Well, useState is what React Hook allows us to access and manipulate states in components. This means we don’t have to be as extendComponent as before.
This is one of several new Hooks coming to the React API that help us write cleaner code. Now let’s use it.
import React, { useState } from "react";
import "./styles.css";
function Form() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<form>
<input
value={firstName}
onChange={e => setFirstName(e.target.value)}
placeholder="First name"
type="text"
name="firstName"
required
/>
<input
value={lastName}
onChange={e => setLastName(e.target.value)}
placeholder="Last name"
type="text"
name="lastName"
required
/>
<input
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="Email address"
type="email"
name="email"
required
/>
<input
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="Password"
type="password"
name="password"
required
/>
<button type="submit">Submit</button>
</form>
);
}
export default Form;
Copy the code
We have created the function component, but there is still some unfamiliar code to explain, especially the four declarations at the top of the component.
Although this part of the code looks strange at first, it’s easy to understand. We no longer declare an object named state to hold the state of the component. Instead, we now divide state into multiple declarations.
If we want to declare a state variable named firstName in the familiar extendsreact.componentmanner, we would normally declare it in the constructor and then access it by writing this.state.firstname.
But with useState, we can initialize two variables named firstName and setFirstName and have their values returned via useState().
Why do we even declare setFirstName?
Since this is a function component, we have no setState to help us change the value of the state variable. We only have setFirstName, whose sole purpose is to update firstName every time it is called.
So when you see:
const [firstName, setFirstName] = useState("")
Copy the code
We’re basically declaring a state variable and a function that allows us to modify the state variable later. The empty string in the useState call is the initial value of firstName, which can be set to any desired value. Now we set it to an empty string.
Note that you can name the setFirstName function however you like. However, there is a convention to append ‘set’ to the name of the state variable we want to modify.
Now we know how to create a state variable in a function component and how to update it. Let’s continue to explain the rest of the code.
In the first input tag, we set its value to the state variable declared at the top of the component. As for the onChange handler, we set it up as an arrow function that updates our status variables.
We had a method called handleInputChange in the previous class component, and now we have an anonymous function that updates the status for us.
Check that everything works by trying to enter text in the form. If all is well, congratulations, you just used a React Hook. If not, go through this tutorial again to make sure you haven’t skipped any instructions.
Add whatever looks good as you see fit.
See the link https://codesandbox.io/s/pp3rp9lqzj? from-embed
reflection
Update: Some people may be shocked by the idea of using inline functions in onClick handlers. I tweeted Dan Abramov and he responded to this part of the Hooks document, explaining why using inline functions in Hooks isn’t such a bad thing.
By examining our new code and comparing it to our old code, it became clear that ReactHooks could help us write better code.
A side-by-side comparison of class and function components makes it clear that function components are easier to reason about, use less code, and generally look cleaner.
If you like ReactHooks, you can learn more by browsing the official documentation and trying to re-implement some projects using them.
That said, I’d like to hear what you think. Do you think Hooks are the future of React, or do you think they’re just unnecessary gimmicks? Leave a comment below.
This article originally appeared on The Andela Way.
The original address: https://medium.freecodecamp.org/how-to-get-started-with-react-hooks-controlled-forms-826c99943b92
Recommended reading
Why is “XX” not a Hooks API?
Async functions and Promise performance optimizations
Everything you need to know about JavaScript timers
Please follow our official account