Introduction to the

Not long ago, React released a new hooks function in the new 16.7.0-alpha.0 release, which allows you to use React state and other functions without using a class component. As we all know, class is sometimes very complicated to write, such as this problem and so on. This article mainly introduces the functions including useState, useEffect, useContext and useRef. This article mainly introduces the functions of these functions.

useState

For example, if you have a component that needs to maintain its state internally, you usually define state when writing a class component, and then use setState to modify its state when you need to modify it. The useState function does just that. It takes an argument initialState, the initialState, and returns an array, the first of which is the current state and the second is the setState equivalent of the previous class component. This function updates state each time it is called and rerenders the current component

function Cunter() {
  const [count, setCount] = useState(0);
  const [title, setTitle] = useState('hello-react');
  console.log('render ===============');
  return (
    <div className="count-box">
      <h1 className="title">Ordered {count}</h1>
      <button onClick={()= > {
        setCount(count + 1);
        setTitle('hello-hooks');
      }}>
        Click Me!
      </button>
      <p>{title}</p>
    </div>)}Copy the code

After clicking button, open the console and see that the two state changes render only once, so useState also merges the state changes in a loop and updates them together. Also, in a function component, useState can be called multiple times, but it doesn’t have to be called this way. Of course, initialState can be an array or an object, so you can change it in a set function just like you would in a class component by calling setState, I think the semantics are clearer.

useEffect

React: componentDidMount (componentDidUpdate); React: componentDidMount (componentDidUpdate); This function takes two arguments, the first is a function that executes after each render, and the function can also return a function that executes after the component is unloaded, similar to the componnentDidUnmount life cycle function for the class component. For example, let’s say we want to get the width of the window in real time and then disable it when the component is uninstalled. Look at the code

function Width() {
    const [width,setWidth] = useState(window.innerWidth);
    const setWidthFn = (a)= > {
        setWidth(window.innerWidth);
    };
    useEffect((a)= > {
        window.addEventListener('resize',setWidthFn);
        return (a)= > {
            window.removeEventListener('resize',setWidthFn)
        }
    });
    return(
        <div>
            <h1>Current window width {width}px</h1>
        </div>)}Copy the code

For example, if a verbose component is render the first time and the value is evaluated according to the ID of the props, it will raise the component every time the props changes. React does this for us, however. We can pass the useEffect function a second argument, ******, so that the request details function will only execute when the ID changes.

function SomeComponent({id}){
  useEffect((a)= > {
    doSomethingWith(id)
  /* The second argument can be passed to more than one dependency, which tells React that the function will be reexecuted if one of the dependencies changes. You can also pass in an empty array, which tells React that the function is executed only once. There is no explanation on the official website as to why the array is passed in. * /
  },[id])
}

Copy the code

useRef

This function will also take an initialState as an argument and return an object, where current is the initialState you passed in. You can pass the returned object as the ref property to the child component to get the DOM object. You can also use it to save the previousProps as follows:

function Counter() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef();
  useEffect((a)= > {
    prevCountRef.current = count;
  });
  const prevCount = prevCountRef.current;
  return (
    <div>
      <h1>Now: {count}, before: {prevCount}</h1>
      <button onClick={setCount(count + 1)} >Click Me!</button>  
    </div>)}Copy the code

useContext

It is easy to use: pass the result returned by React. CreateContext to useContext, and rerender the component when the context changes.

useReducer

This function is exactly the same as Redux.

custom hooks

It is difficult to abstract the logic about state from the original class components and reuse it, but you can do it using hooks. Meanwhile, the React website also says useYourImagination, so specific reuse methods should be combined with actual projects.

Pay attention to

  • Hooks functions allow you to use the function component for many of the class component lifecycle functions, but are not currently supportedgetSnapshotBeforeUpdateandcomponentDidCatch, but cannot be used in class function components, and it is not recommended to mix them in a project to maintain team consistency.
  • It is better to write hooks functions at Top Level in a function component, but it is not necessary to do so. Make sure that every time the component renders, it contains the same hooks function. Do not use hooks based on certain criteria.

Write in the last

Finally, Dan’s React Conf talk about Hooks.

When I started learning React, I thought about the relationship between react logo and React. This project is not called Atom, nor is it a physics engine. One of its explanations is based on reaction, and chemical reactions are based on the performance of atoms in react. However, I found a more reasonable explanation, I think this is the case, the kinds of atoms and attribute determines the performance of the physical reaction and form, the react to let me know if you can separate the user interface into separate individuals, the individual is called components, these components properties and types determine the appearance of the user interface and the special effects. When scientists first discovered the Atom, they thought it was the smallest thing in the world. But it wasn’t long before they discovered the electron, the smaller part of the Atom, which explained a lot more about how the Atom behaves. I think that hooks are like electrons. They are not a new function, they just allow me to use functions that react already knows. State, context, life cycle. I think these were hidden for four years. Now if you look at the React logo, you can see the tracks of the electrons, so the hooks were probably there all along, just like the electron tracks on the logo.