2019年7月31日 星期三


React Hooks Tutorial for Beginners: Getting Started With React Hooks (2019)


In this React hooks tutorial you will learn how to use React hooks, what they are, and why we’re doing it.

React Hooks Tutorial for Beginners: Getting Started With React Hooks (2019)

Here I am, writing a React hooks tutorial for you. I decided to wait until hooks got finally released before dropping this post. Together we’ll learn React hooks step by step, with a look at how the same logic would be implemented with ES6 classes.
Enjoy the reading!

React Hooks Tutorial for Beginners: what you will learn

In the following tutorial you’ll learn:
  • how to use React hooks
  • how the same logic would be implemented in React class components

React Hooks Tutorial for Beginners: requirements

To follow along with the tutorial you should have a basic understanding of:
  • ES6 (arrow functions, destructuring, classes)
  • React

React Hooks Tutorial for Beginners: setting up the project

If you want to follow along with the examples make sure to configure a React development environment. Run:
  1. npx create-react-app exploring-hooks
and you’re good to go!
(You should have one of the latest version of Node.js for running npx).

React Hooks Tutorial for Beginners: in the beginning there was setState

I won’t go too deep here, I assume you’re already using React in your project but let me do a quick recap.
React is a library for building user interfaces and one of its perks is that the library itself imposes a strict data flow to the developer. Do you remember jQuery? With jQuery it’s almost impossible to clearly structure a project, let alone defining how the data should flow across the UI. It’s hard to keep track of what function is changing what piece of UI.
The same applies to plain JavaScript: even if with self-disclipine and practice it’s possibile to come up with a well structured project (thinking about the module pattern), good luck tracking state and interactions between functions (it can be done but it’s hard without external help, see Redux).
These problems has been somewhat eased by React: by enforcing a clear structure (container and functional components) and a strict data flow (components react to state and props change) now its easier than before to create well reasoned UI logic.
So the theory in React is that a piece of UI can “react” in response to a state change. The basic form for expressing this flow was an ES6 class up until now. Consider the following example, an ES6 class extending from React.Component, with an internal state:
  1. import React, { Component } from "react";
  2. export default class Button extends Component {
  3. constructor() {
  4. super();
  5. this.state = { buttonText: "Click me, please" };
  6. this.handleClick = this.handleClick.bind(this);
  7. }
  8. handleClick() {
  9. this.setState(() => {
  10. return { buttonText: "Thanks, been clicked!" };
  11. });
  12. }
  13. render() {
  14. const { buttonText } = this.state;
  15. return <button onClick={this.handleClick}>{buttonText}</button>;
  16. }
  17. }
As you can see from the code above the component’s internal state gets mutated by setStatewhen clicking the button. The text’s button in turns reacts to this change and gets the updated text.
A more concise version of the component can be expressed by removing the constructor thanks to class fields:
  1. import React, { Component } from "react";
  2. export default class Button extends Component {
  3. state = { buttonText: "Click me, please" };
  4. handleClick = () => {
  5. this.setState(() => {
  6. return { buttonText: "Thanks, been clicked!" };
  7. });
  8. };
  9. render() {
  10. const { buttonText } = this.state;
  11. return <button onClick={this.handleClick}>{buttonText}</button>;
  12. }
  13. }
So, in the beginning there was setState (and still it will be). But keep calm. The style above is perfectly fine and ES6 classes in React won’t go away anytime soon.
But now with React hooks it’s possible to express the flow internal state change -> UI reaction without using an ES6 class.
Follow me into the next section …

React Hooks Tutorial for Beginners: updating the state in React … without setState

So what options do we have for managing the internal state in React now that setState and classes are not a need anymore?
Enter the first and most important React hook: useStateuseState is a function exposed by the react package. You will import that function at the top of your files as:
  1. import React, { useState } from "react";
By importing useState in your code you’re signaling the intent to hold some kind of state inside your React component. And more important, that React component shouldn’t be an ES6 class anymore. It can be a pure and simple JavaScript function. This is the most appealing thing of this hooks story.
After importing useState you’ll pick an array containing two variables out of useState, and the code should go inside your React component:
  1. const [buttonText, setButtonText] = useState("Click me, please");
Confused by this syntax? It’s ES6 destructuring. The names above can be anything you want, it doesn’t matter for React. Anyway I advise using descriptive and meaningful variable namesdepending on the state’s purpose.
The argument passed to useState is the actual starting state, the data that will be subject to changes. useState returns for you two bindings:
  • the actual value for the state
  • the state updater function for said state
So the previous example, a button component, with hooks becomes:
  1. import React, { useState } from "react";
  2. export default function Button() {
  3. const [buttonText, setButtonText] = useState("Click me, please");
  4. return (
  5. <button onClick={() => setButtonText("Thanks, been clicked!")}>
  6. {buttonText}
  7. </button>
  8. );
  9. }
For calling the setButtonText state updater inside the onClick handler you can use an inline arrow function. But if you prefer using a regular function you can do:
  1. import React, { useState } from "react";
  2. export default function Button() {
  3. const [buttonText, setButtonText] = useState("Click me, please");
  4. function handleClick() {
  5. return setButtonText("Thanks, been clicked!");
  6. }
  7. return <button onClick={handleClick}>{buttonText}</button>;
  8. }
Must be honest, I fancy regular functions more than arrow functions, unless I have specific requirements. Readability improves a lot. Also, when I write code I think always of the next developer that will mantain that code. And my code should be readable.
React hooks, that’s it! I could end this post here but not before showing you how to fetch data with hooks.
Head over the next section!

沒有留言:

張貼留言