Hooks to define

I’m a Hook. In order to use some of the class-component features of class-component life cycle, state management, and so on in function components, hooks. Note that hooks cannot be used in class components.

Hooks use rules

  • Hooks can only be called from the top level, not from loops, conditional judgments, or nested functions.
If (a===b){useEffect(()=>{//... }, [...]. )}Copy the code
  • Use hooks only in function components, not in class components
  • You can use the eslint-plugin-react-hooks plug-in to regulate the hooks code

Advantages and disadvantages Hooks

advantages

  • Code is easy to reuse (you can customize useState)
  • The code is readable. The code is nicer, each function is in the function with less code
  • Fewer layers of components
  • You don’t have to worry about the direction of this

disadvantages

  • Reactive useEflect, the role of useCalbask, and the timing of the change of the second parameter (the dependency array) are not easy.
  • The states are not synchronized, they’re not on the same UI thread, they’re not on the same variable, they’re showing different values. This can be improved using useRef.
  • State management is error prone
  • You need to know all the hooks functions

Function list

useState

  • Used to declare state variables, similar to this.setState({a:’ ABC ‘}) in the class component. In addition, functions are rendered independently (asynchronously) each time, which is the Capture Value feature
  • The sample
// define const [nameState, setName] = useState(""); Const [age, setAge] = useState(1); / / use the elegantly-named setName (" ABC "); setAge(25);Copy the code
  • pit
  • Click the button to change the value of nameState, and when Enter (or not in the same thread, originally registered method, etc.) is submitted, get the value of nameState, and find that nameState is still the default initial value. For example, click the button to submit and press enter to submit. The value can be obtained by clicking the button to submit, but the value cannot be obtained by pressing Enter to submit.
  • Solutions:
    • Methods a
Const [nameState elegantly-named setName] = useState (); const lastNameState = useRef(nameState); UseEffect (()=>{lastNamestate. current= nameState; }[nameState]); // Call setName const onClick=(e)=>{setName(e.currenttarget.value)}Copy the code
  • Method 2
UseEffect (()=>{setName(name)}, [name]); Const onClick=(e)=>{putName(e.currenttarget.value)} // reducer state const onClick=(e)=>{putName(e.currenttarget.value)} // Action export function putName(name){ return{ type:"CHANGE_NAME", payload: { name } } }Copy the code

useEffect

  • They’re called side effects on the Internet. I don’t know why they’re called side effects ♂️. I prefer response.
  • Its replacement class component declares periodic functions: componentDidMount, componentWillUnmount, componentDidUpdate.
  • The sample
// componentDidMount || componentWillUnmount useEffect(()=>{ // componentDidMount // ... // componentWillUnmount return ()=>{ //... } []); / / componentDidMount | | componentDidUpdate useEffect (() = > elegantly-named setName (name)), [name]); // The name passed from the parent, and when the name changes, nameState is updatedCopy the code

useContext

  • Used to handle multiple levels of data transfer and reduce component nesting.
  • The sample
function Children(){ const color = useContext(colorContext); return <div>{color}</div> } function Parent(){ return <Children/> } const colorContext = createContext("gray"); // React.createContext(); function App(){ return ( <colorContext.Provider value={"red"}> <Parent/> </colorContext.Provider> ) }Copy the code

useReducer

  • Think of it as a scaled-down version of the react-Redux approach. Middleware provided by Redux cannot be used.
  • Can be seen as an alternative to useState
  • UseReducer (reducer, initialState, init ()). Reducer function, receiving state and Action; InitialState is the initial value of state that needs to be set; Init () is a method that initializes state, so you can create the initial state.
  • The sample
const initialState =0;
const init = (v) =>{
    return v;
}

const testReducer =(state, action)=>{
    switch(action){
        case "add":
            return state+1; 
        case"sub":
            return state-1; 
        case "reset":
            return init(action.payload); 
        default:
            return state;
    
    }
}

const[count, calculationDispatch]= useReducer(testReducer, initialState);
// const[count, calculationDispatch] = useReducer(testReducer, initialState, init); 
return(
    <div>
        <div>{count}</div>
        <button onClick={()=>calculationDispatch("add")}>ADD</button>
        <button oClick={()=>calculationDispatch("sub")}>SUB</button>
        <button oClick={()=>calculationDispatch({type: "reset",payload:initialState})}>RESET</button>
    </div>
)
Copy the code

useCallback

  • Gets a memory function to avoid repeated rendering of subcomponents in some cases. Generally used for performance optimization.
  • UseCallback returns a function
  • useCallback(function,[…] ). The first parameter is the number of draws to remember, and the second parameter is function when the values in the array change.
  • The sample
const [text, setText] = useState(""); 
const submit = useCallback(()=>{
    console.log(text)
}, [text]);

return(
    <div>
        <input value={text} onChange={(e)=>setText(e.target.value)}/>
        <button onClick={submit}>Submit</button>
    </div>
)
Copy the code

useMemo

  • Gets a memory component suitable for returning a defined value
  • It is similar to useCallback, except that useCallback returns the function that needs to be executed, whereas useMemo returns the value returned by executing the function
  • The sample
const [text, setText] = useState(""); 
const textMemo = useMemo(()=>{
    return text+"time"
}, [text]);
return(
    <div>
        <input value= {text} onChange={(e)=>setText(e.target.value)}/>
        <input value={textMemo}/>
    </div>
)
Copy the code

useRef

  • Generates a reference to a DOM object.
  • It is similar to createRef, but it is a true reference rather than a copy of the value.
  • Much like useState, it can be thought of as a global variable in render, whereas useState is a local variable in each render; Useref. current does not trigger Ul re-rendering, whereas useState does.
  • The sample
const [name, setName] = useState("");
const nameRef = useRef(name);
const submit =() =>{
    setName(nameRef.current);
}
return(
    <div>
        <p>{name}</p>
        <div>
            <input ref ={nameRef}/> 
            <button onClick={submit}>Submit</button>
        </div>
    </div>
)
Copy the code

useImperativeHandle

  • Penetration Ref is used by the parent component to get a reference to the child component
  • The sample
function ChildInputComponent(props, ref){ const inputRef = useRef(null); useImperativeHandle(re, ()=>inputRef.current); return( <div> <input name="input1" ref={inputRef} placeholder="yes"/> <input name="input1" placeholder="nonono"/> </div>  ) } const ChildInput = forwardRef(ChildInputComponent); function App(){ const inputRef = useRef(null); useEffect(()=>{ inputRef.current.focus() },[]); return( <div> <ChildInput ref={inputRef}/> </div> ) }Copy the code

useLayoutEffect

  • Synchronous execution, which manipulates the DOM after the page is completely rendered, is preferable to the useEffect asynchronous firing function.

other

memo

  • Used to wrap functional components
  • When wrapping a component with React. Memo, the facets are rerendered only when useState or useContext changes within the component.
  • memo(Component, propsAreEqual(preProps, nextProps)); The first parameter is the function component, and the second parameter is the comparison rule. If not passed, the default is the props shallow comparison.

forwardRef

  • Mainly used for DOM penetration
  • The sample
const AButton = React.forwardRef((props, ref)=>( <button ref={ref} {... props}> {props.children}</button> )) class BButton extends React.Component{ this.testRef = React.createRef(); OnClick =()=>{console.log(this.testref.current)}; render(){ return( <div> <AButton ref = {this.testRef} onClick={onClick}>AButtan</AButton> </div> ) } }Copy the code

conclusion

Here is a list of hooks functions that need to be used in order to learn react. Only in the continuous use of a variety of skills, functions, will be more understanding of the more in-depth content.