useState

useState 让函数式组件拥有状态
state 只有在第一次渲染时被创建,之后每次重新渲染都在复用这个 state
setState 可以像在 class 组件里一样传入函数,实现同步更新

  1. import React, { useState } from 'react';
  2. export default function Count() {
  3. const [count, setCount] = useState(0)
  4. return <div>
  5. <div>{count}</div>
  6. <button onClick={() => setCount(count + 1)}>+1</button>
  7. <button onClick={() => setCount((preValue) => preValue - 1)}>-1</button>
  8. </div>;
  9. }

useEffect和useContext

参看文档:https://www.yuque.com/venivici/grlnzp/wsq1to

useReducer

useReducer 只是 useState 的替代,并不是 redux 的替代
不过 useReducer 和 useContext 一起使用可以实现轻量级状态管理取代 redux

  1. import React, { useReducer } from 'react';
  2. const reducer = (state, action) => {
  3. switch(action.type) {
  4. case 'increment':
  5. console.log(action.payload)
  6. return {...state, count: state.count + action.payload}
  7. case 'decrement':
  8. return {...state, count: state.count - action.payload}
  9. default:
  10. return state
  11. }
  12. }
  13. export default function CounterWithReducer() {
  14. const [state, dispatch] = useReducer(reducer, {count: 0})
  15. return <div>
  16. <div>{state.count}</div>
  17. <button onClick={() => dispatch({type:'increment', payload:2})}>+2</button>
  18. <button onClick={() => dispatch({type:'decrement', payload:1})}>-1</button>
  19. </div>;
  20. }

useCallback 和 useMemo

参考文档:https://www.yuque.com/venivici/grlnzp/tneidp

useRef

参考文档:https://www.yuque.com/venivici/grlnzp/ipbwnz

forwardRef 和 useImperativeHandle

参考文档:
https://www.yuque.com/venivici/grlnzp/tneidp
https://www.yuque.com/venivici/grlnzp/lo1tfy