This is the fourth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

What are React Hooks?

From the official website:

Hooks are new in React 16.8. It lets you use state and other React features without having to write a class.

In fact, React has always been highly recommended to use function without side effects to implement components. There are many disadvantages of class components. For example, the mode used is combination instead of inheritance, which violates the original intention of class.

However, implementing components in the form of functions is completely dependent on external state and can’t implement state management itself, which can be tricky for some business scenarios. Before that, we managed the state using redux or writing it inside the class. After the Hook appears, it is possible to manage state within the function.

What problem was solved?

  1. It is difficult to reuse state logic between components
  2. Complex components become difficult to understand
  3. Unintelligible class

The above three points are mentioned by the official, interested students can go to see what the official said. One way to look at it is that the final rendering of a view requires UI+State. In traditional class components, UI and State are intertwined. What if you want to separate them? One is to take some of the states out, encapsulate them into a utils library, but they don’t get into the lifecycle, because they’re static methods.

Redux solves this problem. After the Redux architecture was introduced, the React Component was responsible for UI presentation and Redux was responsible for state management.

import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '.. /actions'

let AddTodo = ({ dispatch }) = > {
  let input

  return (
    <div>
      <form
        onSubmit={e= >{ e.preventDefault() if (! input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }} ><input
          ref={node= > {
            input = node
          }}
        />
        <button type="submit">
          Add Todo
        </button>
      </form>
    </div>
  )
}
AddTodo = connect()(AddTodo)

export default AddTodo
Copy the code

Hooks practice

useState

const [state, setState] = useState(initialState);
Copy the code

In the initial phase, the value of state will be equal to initialState. SetState is used to update the value of state. If state changes, page refresh will be triggered.

useEffect

Similar to a combination of componentDidMount, componentDidUpdate, and componentWillUnmount in a class component, the first argument is a function and the second parameter is a dependency

useEffect(
  () = > {
    const subscription = props.source.subscribe();
    // Return a function that will be called before destruction
    return () = > {
      subscription.unsubscribe();
    };
  },
  [props.source], // Triggers a function call based on a dependency change. Passing [] means that the function is called only once
);
Copy the code

useContext

Receives a context object (the return value of React.createcontext) and returns the current value of the context. Usually we use it with context.provider.

const themes = {
  light: {
    foreground: "# 000000".background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff".background: "# 222222"}};const ThemeContext = React.createContext(themes.light);

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background.color: theme.foreground}} >
      I am styled by theme context!
    </button>
  );
}
Copy the code

summary

  • The advent of React Hooks has given us a better way to modularize our code, and we can move from pulling the public UI away to a more granular split, such as splitting a common logic
  • React Hooks can drastically reduce the amount of code we have to use to understand complex class Components, making everything much easier
  • As long as the Function Component is re-rendered, the code in it will be re-executed, and inline functions and inline objects will be recreated