This does not have a dafang background, but has a positive attitude of people. In this paper, making github.com/qq449245884… Has been included, the article has been classified, also collated a lot of my documentation, and tutorial materials.

Everyone said there was no project to write on the resume, so I found a project for everyone, and I gave it as a bonus【 Building tutorial 】.

  • React New Features and Examples (1)
  • A. Hooks; React; Hooks
  • A. Hooks; React; Hooks

Use the Ref Hooks

Use of Ref in class components:

  • String Ref
  • Callback Ref
  • CreateRef

There is no way to use them in the function component described above, but useRef Hooks are used instead.

There are two main use scenarios for useRef:

  • Gets a handle to a child component or DOM node
  • Storage of shared data between rendering cycles

As you might expect, state can also be saved across the render cycle, but the assignment of state triggers rerendering, whereas ref does not. In this sense, ref is more like a normal member of a class attribute.

To illustrate, get a handle to a child component or DOM node

function TextInputWithFocusButton() { const inputEl = useRef(null); Const onButtonClick = () => {// 'current' points to the text input element mounted to the DOM inputel.current.focus (); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }Copy the code

Essentially, useRef is like a “box” that you can hold a mutable value in its.current property.

An example of millet is: storage of shared data between rendering cycles

function App (props) { const [count, setCount] = useState(0); let it useEffect(() => { it = setInterval(() => { setCount(count => count + 1) }, 1000) } , []) useEffect(() => { if (count >= 5) { clearInterval(it) } }) return ( <div style={{padding:'100px'}}> <h1>{count}</h1>  </div> ) }Copy the code

The above uses useEffect to declare two side effects. The first one increments count by 1 every second, and since it only needs to be done once, each argument is an empty array. The second useEffect determines that count is greater than or equal to, and stops working on the count.

Running result:

When the count is 5, it does not stop. Why?

Because in clearInterval, it is no longer the same variable that was assigned to setInterval, and it will be reset every time the App rerenders. This is where useRef is used to solve the problem.

function App (props) {
  const [count, setCount] = useState(0);
  const it = useRef(null)
  
  useEffect(() => {
    it.current = setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
  } , [])

  useEffect(() => {
    if (count >= 5) {
      clearInterval(it.current)
    }
  })

  return (
    ...
  )
}
Copy the code

Use useRef to create an IT, when the result returned by setInterval is assigned to the CURRENT property of IT.

Running result:

You should be familiar with the REF as the main way to access the DOM. If you pass the ref object into the component as

, React sets the.current property of the ref object to the corresponding DOM node, regardless of how the node changes.

However, useRef() is more useful than the ref attribute **. It can easily hold any variable value **, similar to how instance fields are used in a class.

This is because it creates a normal Javascript object. Instead, useRef() creates a {current:… } object, the only difference is that useRef returns the same REF object every time it is rendered.

Remember, useRef does not notify you when the contents of the ref object change. Changing the.current property does not cause the component to rerender. If you want to run some code when React binds or unbinds a DOM node’s REF, you need to use a callback ref to do so.

Customize the Hook

In the previous three articles, we talked about the three main problems of optimizing class components:

  • Facilitates reuse of state logic
  • Separation of concerns for side effects
  • Function component NonethisThe problem

The reuse state of a component has not been explained much, but it is now explained using custom hooks.

First we wrap the above example with a custom Hook using the count logic:

function useCount(defaultCount) {
  const [count, setCount] = useState(defaultCount);
  const it = useRef()
      
  useEffect(() => {
    it.current = setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
  } , [])

  useEffect(() => {
    if (count >= 5) {
      clearInterval(it.current)
    }
  })
  
  return [count, setCount]
}


function App (props) {
  const [count, setCount] = useCount(0);

  return (
    <div style={{padding: '100px'}}>
      <h1>{count}</h1> 
    </div>
  )
}
Copy the code

Operation effect:

And you can see that it works exactly the same way.

Define a Hook as a function whose name begins with “use”. Other hooks can be called from within the function. It seems that there is no difference between writing a custom function and writing a function component. Indeed, the biggest difference between a custom component and a function component is the difference between input and output.

One more special Hook to deepen the image. With the above code unchanged, we add a custom Hook as follows:

function useCounter(count) {
  return (
    <h1>{count}</h1>
  )
}
Copy the code

In the App component call:

function App (props) {
  const [count, setCount] = useCount(0);
  const Counter = useCounter(count)
  return (
    <div style={{padding: '100px'}}>
      {Counter}
    </div>
  )
}
Copy the code

Operation effect:

We define that the return of useCounter Hook is a JSX, and the operation effect is the same, so the Hook can return JSX to participate in rendering, which further illustrates the similarity between Hook and function component.

Use the law of hooks

Use hooks only at the top level

Never call hooks in a loop, condition, or nest. Be sure to always call them at the top of your React function. By following this rule, you can ensure that hooks are called in the same order every time you render. React can keep the hook state correct between multiple useState and useEffect calls.

Call hooks only in React functions

Instead of calling hooks in a normal JavaScript function, you can:

  • Call Hook in React function component
  • Call another Hook in a custom Hook

Hooks FAQ

The following are some typical problems, which of course are explained on the official website.

How do lifecycle methods correspond to hooks?

  • Constructor: A function component does not require a constructor. You can initialize state by calling useState. If the calculation is expensive, you can pass a function to useState.

  • GetDerivedStateFromProps: Instead schedule an update at render time

  • ShouldComponentUpdate: see [9].

  • Render: This is the function component body itself.

  • ComponentDidMount, componentDidUpdate, componentWillUnmount: useEffect hooks can express combinations of all of these (including less common scenarios).

  • ComponentDidCatch and getDerivedStateFromError: Hook equivalents for these methods are not yet available, but will be added soon.

How do I force an update to a Hooks component

If the values are the same, both useState and useReducer Hook will give up the update. Changing state in place and calling setState will not cause rerendering.

In general, you shouldn’t change local state in React. However, as an alternative, you can use a growing counter to force a rerender even if the state is unchanged:

  const [ignored, forceUpdate] = useReducer(x => x + 1, 0);

  function handleClick() {
    forceUpdate();
  }
Copy the code

Avoid this pattern if possible.

communication

The article is updated every week. You can search “Big Move World” on wechat for the first time to read and hurry up (one or two articles earlier than the blog yo). This article is GitHub github.com/qq449245884… Welcome to Star and improve. You can refer to the exam site for review during the interview. In addition, you can follow the public account and reply welfare in the background, so that you can see the welfare, you know.