Written by Dave Ceddia

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

Until React 16.8, if you wrote a function component and then encountered a situation where you needed to add state, you had to convert the component to a class component.

Write class Thing extends react.ponent, copy the function body into the Render () method, fix the indentation, and finally add the required state.

Today, you can use hooks to get the same functionality and save yourself some work time. In this paper, useState Hook is mainly introduced.

What does useState do

UseState Hook allows us to add state to function components. We usually call these “hooks”, but they are actually functions that are bundled with React 16.8. By calling useState in the function component, a separate state is created.

In a class component, state is always an object on which you can add save properties.

For hooks, state does not have to be an object, it can be any type you want – arrays, numbers, booleans, strings, etc. Each call to useState creates a state block that contains a value.

Example: Use useState to show/hide components

This example is a component that displays some text with a read More link at the end, which expands the rest of the text when clicked.

import React, { useState } from 'react'; import ReactDOM from 'react-dom'; / / two props: Function LessText({text, maxLength}) {// create a state, Const [hidden, setHidden] = useState(true); if (text <= maxLength) { return <span>{text}</span>; } return ( <span> {hidden ? `${text.substr(0, maxLength).trim()} ... ` : text} {hidden ? ( <a onClick={() => setHidden(false)}> read more</a> ) : ( <a onClick={() => setHidden(true)}> read less</a> )} </span> ); } reactdom.render (<LessText text={' Focus, hard work is the real key to success. Keep your eye on the target and take the next step towards the target '} maxLength={35} />, document.querySelector('#root'));Copy the code

With just one line of code, we make this function component stateful:

const [hidden, setHidden] = useState(true);
Copy the code

But what exactly is this function doing? And how it retains state if it is called every render (which it is).

Hooks implementation technique

The “magic” here is that React maintains an object behind each component, and within this persistent object, there is an array of “state units.” When you call useState, React stores the state in the next available cell and increments the array index.

React is able to look for the previous value of a particular useState call, assuming that your hooks always call in the same order (which they would if you followed the rules of hooks). The first call to useState is stored in the first array element, the second in the second element, and so on.

This isn’t all that magical either, mainly because it depends on the fact that you might not have thought about it: the components we wrote are called by React, so it can do some work before calling them. Also, the behavior of a rendering component is not just a function call. JSX like is compiled to react.createElement (Thing) – obviously React can control how and when it is called.

Example: Update status based on previous status

Consider another example: update the value of state based on the previous value.

We’re going to build a pedometer, and every time you click that button, it’s going to tell you how many steps you’ve taken.

import React, { useState } from 'react'; function StepTracker() { const [steps, setSteps] = useState(0); function increment() { setSteps(steps => steps + 1); } return (<div> total {steps} steps! <br /> <button onClick={increment}> </button> </div> ); } ReactDOM.render( <StepTracker />, document.querySelector('#root') );Copy the code

First, create a new state by calling useState and initialize it to 0. It returns the current value of steps 0 and the setSteps function to update the steps and increments the steps by 1 with increment.

Add increment to onClick (int increment, int increment, int increment);

<button onClick={() => setSteps(steps => steps + 1)}>
  I took another step
</button>
Copy the code

Example: State as an array

Remember, state can hold any value you want. Here is an example of a list of random numbers. Clicking the button adds a new random number to the list:

function RandomList() {
  const [items, setItems] = useState([]);

  const addItem = () => {
    setItems([
      ...items,
      {
        id: items.length,
        value: Math.random() * 100
      }
    ]);
  };

  return (
    <>
      <button onClick={addItem}>Add a number</button>
      <ul>
        {items.map(item => (
          <li key={item.id}>{item.value}</li>
        ))}
      </ul>
    </>
  );
}
Copy the code

Note that we initialize state to an empty array [] and update the value in the addItem function.

SetItems updating state does not “merge” old values – it overwrites state with new values. This is different from how this.setState works in a class.

Example: State with multiple keys

For the state object example, create a login form with two fields: username and password.

The following example focuses on how to store multiple values in a state object and how to update a single value.

function LoginForm() { const [form, setValues] = useState({ username: '', password: '' }); const printValues = e => { e.preventDefault(); console.log(form.username, form.password); }; const updateField = e => { setValues({ ... form, [e.target.name]: e.target.value }); }; return ( <form onSubmit={printValues}> <label> Username: <input value={form.username} name="username" onChange={updateField} /> </label> <br /> <label> Password: <input value={form.password} name="password" type="password" onChange={updateField} /> </label> <br /> <button>Submit</button> </form> ); }Copy the code

If you want to try it, check out CodeSandbox.

First, we create a state fragment and initialize it with an object

const [form, setValues] = useState({
  username: '',
  password: ''
})
Copy the code

This looks like a way to initialize state in a class.

There is also a function that handles submissions, where e.preventDefault prevents page refreshes and prints out form values.

The updateField function is more interesting. It passes an object using setValues. To ensure that the existing state is not overwritten, an expansion operation is used (… The form).

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: daveceddia.com/usestate-ho…

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.