Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
📢 Hello everyone, I am Xiao Cheng, a sophomore front-end enthusiast
📢 This article is a study note for the section on Learning React hooks
📢 Thank you very much for reading
📢 May you be true to yourself and love life
The meaning of which hooks exist
-
The state between hooks is separate and has its own context; there is no state confusion
-
Let the function have state management
-
The component tree is not intuitive, class components are difficult to maintain, logic is not easy to reuse problems
-
Avoid the side effects of repeated function execution
Application scenarios
- Replace life cycle functions with hooks
- Let the component have state
- Component helper function
- Processing send requests
- Access data
- Optimize performance
hooks API
We import it from React
1. useState
Adds state to function components
- Initialize and update the component state
const [count, setCount] = React.useState(0)
Copy the code
Takes an argument as an initial value and returns an array: the first is the state variable, and the second is the function that modifies the variable
2. useEffect
Side effects of hooks
- Add a signal to end rendering for components that have no life cycle
Note:
- Hooks executed after render
The first parameter receives a function that is executed when the component is updated
The second argument takes an array of variables to track, a list of dependencies, and updates only when dependencies are updated
The return value of the first argument, which returns a function, is executed before useEffect is executed
It is generally used to add destruction events so that only one can be added
React.useEffect(() = > {
console.log('Called');
return () = > {
console.log('I'm about to be unloaded.');
}
}, [count])
Copy the code
3. useLayoutEffect
This is similar to useEffect
This is used to perform an operation after a DOM update is complete
Note:
- Hooks with DOM manipulation side effects
- Execute after DOM update
UseEffect is executed before useEffect. All other uses are the same as useEffect
UseEffect executes after Render
UseLayoutEffect is executed after DOM update
4. useMemo
Function: Allows a function in a component to follow status updates
Note: Optimize the function function in the function component
To avoid forced execution of the current function due to other status updates
The first argument takes a function, and the second argument, an array of dependencies, returns a value
const getDoubleNum = useMemo(() = > {
console.log('ddd')
return 2 * num
}, [num])
Copy the code
5. useCallback
Effect: Executes following status updates
Note:
- It is executed only if the dependency changes
useMemo( () => fn, deps)
The equivalent ofuseCallback(fn, deps)
Difference:
useCallback
It returns a function, not a valueuseCallback
The cache is a function,useMemo
The cache is a value,If the dependency is not updated, the cached function is always returned- To child components
props
If the current component is not updated, re-rendering of child components will not be triggered
6. useRef
Function: Save data for long time
Matters needing attention:
- Returns an index of child elements that remains constant throughout the life cycle
- Object changes are not notified, and property changes are not re-rendered
- Save a value that remains constant throughout its life cycle
- To assign a value
ref.current
Rerender will not trigger - It creates an extra container to store the data, and we can get the value externally
When we get the id of the timer in the normal way, we cannot get it, we need to get it through ref
useEffect(() = > {
ref.current = setInterval(() = > {
setNum(num= > num + 1)},400)
}, [])
useEffect(() = > {
if (num > 10) {
console.log('It's ten');
clearInterval(ref.current)
}
}, [num])
Copy the code
7. useContext
What it does: Render with subcomponents
Note:
- A change in the upper-level data will definitely trigger a re-rendering
- We need to introduce
useContext
å’ŒcreateContext
Two content - through
createContext
To create aContext
handle - through
Provider
Determine the scope of data sharing - through
value
To distribute the data - In the child component, pass
useContext
To get the data
import React, { useContext, createContext } from 'react'
const Context = createContext(null)
export default function Hook() {
const [num, setNum] = React.useState(1)
return (
<h1>This is a function component - {num} // scoping<Context.Provider value={num}>
<Item1 num={num} />
<Item2 num={num} />
</Context.Provider>
</h1>)}function Item1() {
const num = useContext(Context)
return <div>Subcomponent 1 {num}</div>
}
function Item2() {
const num = useContext(Context)
return <div>Subcomponent 2 {num}</div>
}
Copy the code
8. useReducer
Purpose: To borrow resources from other places
Note: Function component’s Redux operation
- Creating a data warehouse
store
And managersreducer
- through
useReducer(store,dispatch)
In order to getstate
å’Œdispatch
const store = {
num: 10
}
const reducer = (state, action) = > {
switch (action.type) {
case "":
return
default:
return}}const [state, dispatch] = useReducer(reducer, store)
Copy the code
Dispatch actions via Dispatch
9. Customize hooks
Put it in the utils folder and name it starting with use
For example: Hooks that simulate data requests
import React, { useState, useEffect } from "react";
function useLoadData() {
const [num, setNum] = useState(1);
useEffect(() = > {
setTimeout(() = > {
setNum(2);
}, 1000); } []);return [num, setNum];
}
export default useLoadData;
Copy the code
Reduce code coupling
We want the Reducer to be used by each component, we write a hooks ourselves
Customize a LocalReducer of your own
import React, { useReducer } from "react";
const store = { num: 1210 };
const reducer = (state, action) = > {
switch (action.type) {
case "num":
return { ...state, num: action.num };
default:
return{... state }; }};function useLocalReducer() {
const [state, dispatch] = useReducer(reducer, store);
return [state, dispatch];
}
export default useLocalReducer;
Copy the code
- Introduce React and the hooks you need
- Create your own hook functions
- Returns an array in which the first content is data and the second is a function that modifies the data
- Expose custom hook functions out
- Introduce your own business components