React Hooks notes 1

useState

const [state, setSate] = useState(initialState)

feature:

  • setState identify stable and will not change when the component is re-rendered, the first value useState return is always the latest state

  • If the object is the state, only when the update subject section attributes, the object does not merge state update

  • If the state does not change, the call will skip the update setState

Recommendation: The same time update state, combined with initialization

Functional initialization state

const [state, setState] = useState(()=>{
    const initialState = someExpensiveComputation(props)
    return initialState
})

Update state objects

setState((preState)=>{
    return {...prevState, ...updatedValues};
})

useEffect

Asynchronous callback after useEffect component rendering, render and perform before the next

Synchronous callback after useLayoutEffect component rendering

useEffect (the callback) // components each rendering, is regenerated useEffect 
useEffect (the callback, [dependent parameter]) // assembly after each rendering, according to regenerate dependent parameter is determined whether useEffect 
useEffect (the callback, []) // only run once when the component mount

useEffect Hook corresponding life cycle:

  • componentDidMount

  • componentDidUpdate

  • componentWillUnmount

Dependency frequently change measures (official cited the example):

function Counter () { 
  const [COUNT, setCount] = useState (0 ); 

  useEffect (() => { 
    const ID = the setInterval (() => { 
      setCount (C => C +. 1); // ✅ functional setCount change, no dependencies 
    }, 1000 );
     return () => the clearInterval (ID); 
  }, []); // 

  return <h1 of> {COUNT} </ h1 of>; 
}

useReducer

Scenario:

  • Manage internal state

  • Binding context, to avoid the use of dispatch parent component is passed down callback

React.createContext TodosDispatch = const ( null );
 // parent component 
function TodosApp () {
   // Tip: `dispatch` re-rendering does not change between 
  const [Todos, dispatch] = useReducer (todosReducer);
   return (
     <TodosDispatch = {value} dispatch .Provider> 
      <DeepTree /> 
    </TodosDispatch.Provider>   ); 
} // subassembly function DeepTree (The props) {
   // Get dispatch. 
  dispatch = const useContext (TodosDispatch); function the handleClick () { 
    dispatch ({type: 'the Add', text: 'Hello' }); 
  }




  

  return (
    <button onClick={handleClick}>Add todo</button>
  );
}

Function initialized (official cited the example)

function init(initialCount) {
  return {count: initialCount};
}

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    case 'reset':
      return init(action.payload);// 重新初始化 state,没用用到上一个state
    default:
      throw new Error();
  }
}

function Counter({initialCount}) {
  const [state, dispatch] = useReducer(reducer, initialCount, init);
  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({type: 'reset', payload: initialCount})}> // 传入参数

        Reset
      </button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

useCallback

For performance optimization

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);

useMemo

For performance optimization, the incoming function is executed when the component rendering

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

useRef

refContainer = const useRef (the initialValue);
 // refContainer as ref objects 
// refContainer.current any variable value may be stored

feature

  • useRef returns to the same object rendering ref

  • Change .currentattribute will not lead to re-render the component

How to detect changes in the DOM element? (Official example)

function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  }, []);// 检测 ref 的回调函数

  return (
    <>
      <h1 ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(height)}px tall</h2>
    </>
  );
}

Custom Hook

 

Rules: function must "use .." defined at the beginning, you can call other internal Hook

Hook for disengagement sharing logic and encapsulate complex: scenarios

feature:

  • The different components common custom Hook, not shared state

  • Custom components can be called many times Hook

  • Information may be transferred between the Hook (state within the incoming custom assembly Hook, custom Hook state will change with the updated)

Guess you like

Origin www.cnblogs.com/seny-33/p/12219491.html
Recommended