Function of React Hooks

EDITORIAL

In 2018 React Conf Conference, React team explained some of the problems we currently use React existing development process and introduced a concept exciting: React Hooks, hooks and how to solve these problems. My team just where the front-end using react + ts + node this technology stack, some time ago to upgrade react to version 16.8, using hooks to function in this process. Write your own feelings and opinions.

This paper will summarize the following sections:

  1. What pain points exist before React Hooks?
  2. React Hooks bring the code patterns change
  3. to sum up
  4. Further reading

What pain points exist before React Hooks?

Similar logic assembly 1. Room multiplexed difficult

Prior to react hooks come out, react between the components can provide multiplexing logic uses a mixin, but this way the drawbacks very much, so we basically use render props (rendering attributes) and HOC (high-order components) to multiplex between the logical components. But the disadvantage is also very obvious in two ways, it is easy to generate "wrapper hell", that is, the component is easy bloated, increasing the cost of the debugger.

Question 2. Life Cycle

In slightly more complex business logic among life cycle is not around the past. There are a lot of logic in componentDidmount treated at the scene had to deal once again in componentDidUpdate, business is scattered in various different life cycle function.

The Hooks appears, from facing life cycle programmed into a business-oriented logic programming

3. people and machines are not friendly class

Although it is possible to write purely functional components before Hooks, but it can only be stateless. Very often the case that you write a pure function component, but over time you have to find plus a state, this time had to be replaced by purely functional component class components. At this time we have to deal with this problem, but the compiler class is unfriendly.

React Hooks bring the code patterns change

import { useState, useEffect } from 'react' 
function Example(props) {
  // 声明一个新的状态变量"count" 
  const [count, setCount] = useState(0);

  useEffect(() => {
    subscribe(props.number, setCount)
    return () => {
      unsubscribe(props.number)
    }
  })

  return <div>{count}</div>
}
复制代码

useState accept an initial value, and then returns a [ status, Status Modifier ] tuple. Each time re-render the entire function will be re-run, but useState remembers the last values. And react according to the order useState call to remember the state of attribution:

const Example = () => {
    const [size, setSize] = useState({ width: 100, height: 100 });
    const [count, setCount] = useState(0);   
}
复制代码

Each Example is rendered, is the first time useState calls to get the size and setSize, second useState calls to get the count and setCount.

useEffect is used to treat side effects, equivalent to the previous componentDidMount and componentDidUpdate. It can return a function to be called before the assembly to uninstall. Therefore, the polymerization operation useEffect componentDidMount, componentDidUpdate and the componentWillUnmount. If props.number not changed, we do not want useEffect subscribe / unsubscribe in the re-run, in order to realize this operation, only you need to pass a parameter.

  useEffect(() => {
    subscribe(props.number, setCount)
    return () => {
      unsubscribe(props.number)
    }
  }, [props.number])
复制代码

It is an array, as long as each value in the array do not change, you do not need to re-execute useEffect.

After the upgrade will react, life cycle functions migrate to the function components can operate in the following manner:

  • constructor: Use useState to initialize state.
  • getDerivedStateFromProps: function module itself can be directly manipulated.
  • shouldComponentUpdate: 使用 React.memo。
  • render: function of the component itself.
  • componentDidMount, componentDidUpdate, componentWillUnmount: Use useEffect achieve.

In the process of development react hooks, the shared code in the form of function components. Agreed to use the beginning of the useXXX, would like to reuse code, the functional components can useXXX by calling.

For example, we can write a useMountLog, print out a log of when the component mount:

const useMountLog = (name) => {
    useEffect(() => {
        console.log(`${name} mounted`);    
    });
}
复制代码

As a result, all of the functional components can use this feature by calling useMountLog:

const Example = () => {
    useMountLog('Example')
}
复制代码

Another example may be reflected in the current window by writing a custom useWindowWidth such hook width

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  });
  
  return width;
}
复制代码

This may be used in other functional components:

function MyResponsiveComponent() {
  const width = useWindowWidth();
  return (
    <p>Window width is {width}</p>
  );
}
复制代码

Can be seen in the example above, react hooks greatly reduce our amount of code. The hooks can only be used in functional components, it is possible to predict although it still supports class components react, but after class components will slowly die out too.

to sum up

React Hooks appears, will greatly reduce the amount of code react to solve some of the problems encountered in the development of the original use of react, but also to the development brought some changes. include:

  • react hooks will change the way code reuse between components. Use custom hooks, no confusion mixin brought no hierarchy abyss HOC brings.
  • Programming for the life cycle of the business-oriented programming logic
  • No longer need to class, no longer need to focus on this and other issues

Finally, citing Dan Abramov speeches on the end of this article React Conf 2018:

"...... I used to wonder why React's Logo is an atom? Then I thought of this explanation. We know that matter is made of atoms, is characteristic of atoms determines the appearance and behavior of matter. Like React, you can view the user split into separate components, like atoms and then combine as free, are characteristics of the assembly determines the behavior of the user view. scientists once thought that the atom was the smallest indivisible unit, until the discovery of the electron, inside an atomic smaller particles. in fact, the impact is characteristic of the electronic properties of atoms. I think hooks like electronics, it is not so much a new feature, as it is known React properties (state, context, lifecycle) of more direct to show the form, which is four years we have been turning a blind eye to it.

If the logo staring React look at it, you will find hooks actually been in. "

Further reading

Making Sense of React Hooks

React Today and Tomorrow and 90% Cleaner React

Some Thoughts on the React Hooks

Reproduced in: https: //juejin.im/post/5cfb1e12f265da1b8a4f0f1e

Guess you like

Origin blog.csdn.net/weixin_33736048/article/details/91442959