React: React React: React React

What is the point of adding Hooks to React? Or why did React include Hooks? Finally, a basic implementation of Hooks;

First, let’s take a look at the basic use of two Hooks, which are typically used in code that is not covered here.

UseState basic use:

/ / introduce useState
import React, { useState } from 'react'

function App() {
  / / use
  const [count, setCount] = useState(1);
  return (
    <div>
      <h2> useState </h2>
      <p>{count}</p>
      {/* 调用 setCount方法 */}
      <button onClick={()= >SetCount (count + 1)}> add 1</button>
    </div>)}export default App

Copy the code

UseEffect:

import React, { useState, useEffect } from 'react'
import ReactDom from 'react-dom'

function App() {
  const [count, setCount] = useState(1)

  // Execute after component mount is complete && execute after component data update is complete
  // useEffect(() => {
  // console.log('666')
  // })


  // Execute after the component is mounted
  // useEffect(()=>{
  // console.log(678)
  / /} []),


  // Execute before the component is uninstalled (introduce react-dom for uninstallation tests)
  useEffect(() = >{
    return () = >{
      console.log('Component unmounted')}})return (
    <div>
      <h2>useEffect</h2>
      <p>{count}</p>
      <button onClick={()= >SetCount (count + 1)}> add 1</button>{/* Uninstall components */}<button onClick={()= >ReactDom. UnmountComponentAtNode (document. GetElementById (" root "))} > uninstall components</button>
    </div>)}export default App

Copy the code

Going back to the previous question, there is no standard answer to this question, but we can put ourselves in the interviewer’s shoes and think about why they ask this question. To examine the basic use of Hooks and our own personal reflections on the Hooks design philosophy; The React document provides the answer, but many people just don’t read it. React (docschina.org)

The “motivation” in the document explains why React adopted Hooks, which are: 1. Logic between components is hard to reuse; 2. 2. Large and complex components are difficult to split. 3. The use of Class syntax is unfriendly.

In general, it is actually the class component in years of application practice, found many unavoidable problems and difficult to solve, and relative to the class component, function component is too simple, for example, class component can access the life cycle method, function component can not; State can be defined and maintained in class components, but not in function components; Class components can get instantiated this and do all sorts of things based on this, but function components can’t;

But functional programming methods, in the JS is a Class of object oriented way more friendly and intuitive, so as long as the function of the component can ability is lacking, and solves the above problem, and if directly modify the ability of function component, is bound to cause a greater cost, the best way is to open to call the corresponding interface, Non-intrusive introduction of component capabilities, which we now see as Hooks;

Which of these are the Hooks that solve the problems in class components and function components without which Hooks are used. Which of these are the Hooks that solve the problems in function components? That is what Hooks are for, so on to the next question, what are the Hooks’ design ideas? Using code that mimics a basic Hooks implementation, we override useState:

import React from 'react'
// Import the DOM to update the component
import ReactDom from 'react-dom'

let state
function useState(initState) {
  // Check whether state is initialized
  state = state ? state : initState
  function setState(newState) {
    // Update data
    state = newState
    // Call the function to update the component
    render()
  }

  return [state, setState]
}

// Re-render the component
function render() {
  ReactDom.render(<App />.document.getElementById('root'))}function App() {
  // Use custom useState
  const [count, setCount] = useState(1);

  return (
    <div>
      <p>{count}</p>
      <button onClick={()= >SetCount (count + 1)}> add 1</button>
    </div>)}export default App

Copy the code

Rudi Yardley wrote an article in 2018 called “React hooks: Not Magic, Just Arrays explains its design principle in detail. If you are interested, you can find it. The above case is actually used in the article. Count starts with 1, then useState assigns the initial value and gets the current state and the function setState. Call setCount when the button is clicked to change the value of count. Essentially, a state hook replaces the role of setState in a class component.

Under normal circumstances, a passionate statement is followed by value, so let’s do one;

The React team knows that adding a brand new concept is a high learning cost for us developers, so the React team has prepared a detailed comment document for curious readers, which discusses in more detail the motivation for advancing the React project. It also provides additional perspectives on specific design decisions and related advanced technologies.

Most importantly, hooks and existing code work together, and you can use them gradually. There is no rush to migrate to Hook. We recommend avoiding any “wholesale rewriting,” especially for existing, complex class components. Before you can start “thinking Hook,” you need to make some mental shifts.