useState
保存状态const [msg, setMsg] = useState("hello hooks");
useEffect
副作用useEffect(() => {
// 执行
return () => {
// 取消
}
}, [//依赖项])
useContext(XXXContext)
接获取某个Context的值// context.js
import { createContext } from 'react';
const UserContext = createContext();
const ThemeContext = createContext();
export default {
UserContext, ThemeContext
}
// App.jsx
<UserContext.Provider value={{name: 'xiaoming', age: 18}}>
<ThemeContext.Provider value={{color: 'red', size: 12}}>
<App>
</ThemeContext.Provider>
</UserContext.Provider>
// Function Comp
export default () => {
const USER = useContext(UserContext);
const THEME = useContext(ThemeContext);
return (<>
<h2>{USER.name}-{USER.age}</h2>
<h3 style={{color: THEME.color, size: THEME.size}}>content</h3>
</>)
}
userReducer()
管理负责数据, useState的替代品,而非redux的替代品// const [state, dispatch] = userReducer(reducer, initState);
import React, { memo, userReducer } from 'react';
function reducer(state, action){
switch(action.type){
case 'add':
return {...state, counter: state.counter + action.payload};
case 'sub':
return {...state, counter: state.counter - action.payload};
default:
return state;
}
}
export default memo(() => {
const [state, dipatch] = useReducer(reducer, {counter: 0});
return <>
<h2>counter: {state.counter}</h2>
<button onClick={() => dispatch({type: 'add', payload: 5})}>+5</button>
<button onClick={() => dispatch({type: 'sub', payload: 5})}>-5</button>
</>
})
useCallback
记忆化回调函数,useMemo
useCallback
会返回一个函数的 memoized
(记忆的) 值;在依赖不变的情况下,多次定义的时候,返回的值是相同的;
作为参数传递给子组件时使用
;const fn = useCallback(() => {
dosomething(a, b);
}, [a, b]);
配合useRef使用
;const [count, setCount] = useState();
const countRef = useRef();
countRef.current = count;
const addFn = useCallback(() => setCount(countRef.current + 1), []);
useMemo(() ={}, [dep])
对回调函数的结果进行缓存
useCallback(fn,[dep]) = useMemo(() => fn, [dep])
- 进行大量的计算操作,是否有必须要每次渲染时都重新计算;
- 对子组件传递相同内容的对象时,使用useMemo进行性能的优化
useRef
返回一个ref对象,返回的ref对象再组件的整个生命周期保持不变。useImperativeHandle
子组件向父组件传递特定的对象
const SonComponent = memo(forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(() => {
return {
focus(){
inputRef.current.focus();
}
setValue(val){
inputRef.current.value = val;
}
} //返回的这个对象会被绑定到ref.current
})
return (<>
<h2>son component<h2>
<input ref={inputRef}/>
</>)
}))
const FatherComponent = memo(() => {
const sonRef = useRef();
return (<>
<h1>father comp</h1>
<SonComponent ref={sonRef} />
</>)
})
useLayoutEffect()
useFn
,内部可以使用其他hook// 获取滚动位置
export function useWindomPosition(){
const [position, setPosition] = useState();
const handleScroll = () => {
setPosition(window.scrollY);
}
useEffect(() => {
document.addEventListener('scroll', handleScroll);
return () => {
document.removeEventListener('scroll', handleScroll);
}
})
return position;
}
// 使用localStorage存储数据
export function useLocalStorage(key){
const [data, setData] = useState(() => JSON.parse(window.localStorage.getItem(key)));
useEffect(() => {
window.localStorage.setItem(key, data);
}, [data]);
return [data, setData];
}
useSelector
将state映射到组件中;useDispatch
直接获取dispatch函数;useStore
获取store对象;
// 1.获取state
import { useSelector, useDispatch, shallowEqual } from 'react-redux';
const { count } = useSelector((state) => {
return {
count: state.counter.count
}
},shallowEqual)
useId
用于生成横跨服务端和客户端的稳定的唯一 ID 的同时避免 hydration 不匹配的 hook。
useTransition
返回一个状态值表示过渡任务的等待状态,以及一个启动该过渡任务的函数。告诉react对于某部分任务的更新优先级较低,可以稍后进行更新。
useDeferredValue
接受一个值,并返回该值的新副本,该副本将推迟到更紧急地更新之后。