React Hooks basic usage

React has too many ways to write react. Is learning

The React team wanted components not to become complex containers, but rather conduits for data flow. Developers can assemble pipes as needed. A component is best written as a function, not a class. (It’s more convenient to go with the flow)

UseState status hook

The component Two changes the value of count in One

function One (props) {
const [count, setCount] = useState(0)
return (
 <div>this is one  {count}<Two {.{ count.setCount}} ></Two> </div>)}function Two (props) {
const { setCount, count } = props
return <div>this is Two  <button onClick={()= > { setCount(count + 1) }}>click it!</button> </div>
}
Copy the code

UseContext Shared state hook

const OneContext = createContext({})
function One (props) {
  return (
    <OneContext.Provider value={{ name: "this is onecontext}} ">
      <div>this is one <Two ></Two> </div>
    </OneContext.Provider>
  )
}

function Two (props) {
  const { name } = useContext(OneContext)
  return <div style={{ 'color': 'red' }}>this is Two {name}  </div>
}
Copy the code

UseReducer () : Action hook

const reducer = (state, action) = > {
  switch (action.type) {
    case 'one':
      return { ...state, count: state.count + 1 }
    case 'two':
      return { ...state, count: state.count + 2}}}function One (props) {
  const [state, dispatch] = useReducer(reducer, { count: 0 })
  return (

    <div>this is one
       <button onClick={()= > { dispatch({ type: 'one' }) }}>+1</button>
       <Two dispatch={dispatch}></Two>{state.count} </div>)}function Two (props) {
  const { dispatch } = props
  return <div style={{ 'color': 'red' }}>this is Two  
         <button onClick={()= > { dispatch({ type: 'two' }) }}>+2</button></div>
}

Copy the code

UseEffect () : Side effect hook

PS: This thing is great to use. Very simple, very useful, replacing some life cycle

useEffect(() => {
    console.log('this is effect')}, [])Copy the code

UseEffect () takes two arguments. The first argument is a function in which the code for asynchronous operations is placed. The second argument is an array that gives the Effect dependencies, and useEffect() is executed whenever this array changes. The second argument can be omitted, in which case useEffect() is executed every time the component renders, or only once if the array is passed empty

UseMemo, useCallback

Avoid overrendering problems depending on the situation