概念+示例+横向对比+难点解析征服八大react hooks
    		       		warning:
    		            这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
    		        
        		                
                React Hooks 是 React 16.8 的新增特性,它可以让你在函数组件中使用 state 以及其他的 React 特性。以下是八种常用的 React Hooks,以及它们的概念、示例、横向对比和难点解析。
- useState
import React, { useState } from 'react';
 
function Example() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}- useEffect
import React, { useState, useEffect } from 'react';
 
function Example() {
  const [count, setCount] = useState(0);
 
  // 类似于类中的componentDidMount和componentDidUpdate:
  useEffect(() => {
    // 更新文档的标题
    document.title = `You clicked ${count} times`;
  });
 
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}- useContext
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
 
function Button() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}- useReducer
import React, { useReducer } from 'react';
 
function Example() {
  const [state, dispatch] = useReducer(reducer, initialState);
 
  function handleIncrementClick() {
    dispatch({ type: 'increment' });
  }
 
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={handleIncrementClick}>Increment</button>
    </div>
  );
}
 
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    default:
      throw new Error();
  }
}- useCallback
import React, { useCallback } from 'react';
 
function Example() {
  const memoizedCallback = useCallback(() => {
    doSomething(a, b);
  }, [a, b]);
 
  return <SomeComponent onSomething={memoizedCallback} />;
}- useMemo
import React, { useMemo } from 'react';
 
function Example() {
  const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
 
  return <div>{memoizedValue}</div>;
}- useRef
import React, { useRef } from 'react';
 
function Example() {
  const ref = useRef(null);
 
  function handleClick() {
    ref.current.focus();
  }
 
  return (
评论已关闭