useRef
import { useEffect, useRef } from "react";
function UseRef() {
const btnRef = useRef(null) // 初始值
useEffect(() => {
console.log(btnRef.current); // DOM 节点
}, [])
return <div>
<button ref={btnRef}>click</button>
</div>
}
export default UseRef;
useContext
import React, { useContext} from "react"
const themes = {
light: {
foreground: '#000',
background: '#fff'
},
dark: {
foreground: '#fff',
background: '#222'
}
}
// 创建 context
const ThemeContext = React.createContext(themes.light)
function App() {
return <ThemeContext.Provider value={themes.light}>
<ToolBar></ToolBar>
</ThemeContext.Provider>
}
function ToolBar() {
return <div>
<ThemeBtn />
</div>
}
function ThemeBtn() {
const theme = useContext(ThemeContext);
return <button style={{background: theme.background, color: theme.foreground}}>总是很奇妙的
一旦你努力去做一件事
如果结果不是你想象的那样
那么老天
一定会给你一个
更好的结果</button>
}
export default App
useReducer 代码演示
import { useReducer } from "react";
const initState = {
count: 0
}
const reducer = (state, action) => {
switch (action.type) {
case 'add':
return { count: state.count + 1 }
case 'dec':
return { count: state.count - 1 }
default:
return state;
}
}
function App() {
// 很像 const [count, setCount] = useState(0)
const [state, dispatch] = useReducer(reducer, initState);
return (<div>
{state.count}
<button onClick={() => dispatch({type: 'add'})}>add</button>
<button onClick={() => dispatch({ type: 'dec'})}>dec</button>
</div>)
}
export default App;
useReducer 和 redux 的区别
- useReducer 是 useState 的代替方案,用于 state 复杂变化
- useReducer 是单个组件状态管理,组件通讯还需要 props
- redux 是全局的状态管理,多组件共享数据
useMemo
- React 默认父组件有变化,子组件无条件更新
- class 组件使用 SCU 和 PureComponent 做优化
- Hooks 总使用 useMemo,但优化的原理相同 ```jsx import { useState, memo, useMemo } from “react”;
// function Child({ userInfo }) {
// console.log(child run ${userInfo}
);
// return
{userInfo.name},{userInfo.age}
// }// 类似class组件PureComponent,对 props 进行浅层比较
const Child = memo(({ userInfo }) => {
console.log(child run ${userInfo}
);
return
{userInfo.name},{userInfo.age}
})function App() { console.log(‘parent run’); const [count, setCount] = useState(0); const [name, setName] = useState(‘pw’);
// const userInfo = { // age: 23, // name // }
// 用 useMemo 缓存数据 // 有依赖 const userInfo = useMemo(() => { return { age: 22, name } }, [name])
return <>
useCallback
- useMemo 缓存数据
- useCallBack 缓存函数
- 两者都是 React Hooks 的常见优化策略