useRef

  1. import { useEffect, useRef } from "react";
  2. function UseRef() {
  3. const btnRef = useRef(null) // 初始值
  4. useEffect(() => {
  5. console.log(btnRef.current); // DOM 节点
  6. }, [])
  7. return <div>
  8. <button ref={btnRef}>click</button>
  9. </div>
  10. }
  11. export default UseRef;

useContext

  1. import React, { useContext} from "react"
  2. const themes = {
  3. light: {
  4. foreground: '#000',
  5. background: '#fff'
  6. },
  7. dark: {
  8. foreground: '#fff',
  9. background: '#222'
  10. }
  11. }
  12. // 创建 context
  13. const ThemeContext = React.createContext(themes.light)
  14. function App() {
  15. return <ThemeContext.Provider value={themes.light}>
  16. <ToolBar></ToolBar>
  17. </ThemeContext.Provider>
  18. }
  19. function ToolBar() {
  20. return <div>
  21. <ThemeBtn />
  22. </div>
  23. }
  24. function ThemeBtn() {
  25. const theme = useContext(ThemeContext);
  26. return <button style={{background: theme.background, color: theme.foreground}}>总是很奇妙的
  27. 一旦你努力去做一件事
  28. 如果结果不是你想象的那样
  29. 那么老天
  30. 一定会给你一个
  31. 更好的结果</button>
  32. }
  33. export default App

useReducer 代码演示

  1. import { useReducer } from "react";
  2. const initState = {
  3. count: 0
  4. }
  5. const reducer = (state, action) => {
  6. switch (action.type) {
  7. case 'add':
  8. return { count: state.count + 1 }
  9. case 'dec':
  10. return { count: state.count - 1 }
  11. default:
  12. return state;
  13. }
  14. }
  15. function App() {
  16. // 很像 const [count, setCount] = useState(0)
  17. const [state, dispatch] = useReducer(reducer, initState);
  18. return (<div>
  19. {state.count}
  20. <button onClick={() => dispatch({type: 'add'})}>add</button>
  21. <button onClick={() => dispatch({ type: 'dec'})}>dec</button>
  22. </div>)
  23. }
  24. 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 <> </> }

export default App; ```

useCallback

  • useMemo 缓存数据
  • useCallBack 缓存函数
  • 两者都是 React Hooks 的常见优化策略