hieunguyen
12/6/2019 - 10:47 AM

React Hook Personnal note

Notes

  1. hook is a function, being called on the top on the function react component, giving more feature / state into that function componentsds
  2. Most of the time hook will start with use i.e useBlabla()
  3. there are 2 hook being built-in so far
    • useState:

      • adding variable into component state
      • Usage
      // parameter of useState will be default value of `count`
      // setCount is a function taking 1 parameter to update the count 
      const [count, setCount] = useState(0);
      
    • useAffect:

      • adding side affect when component's props/state changed
      • there is 2 type of affect: need clean up and not needed clean up
      • Example of the one does not need clean up
      useEffect(() => {
        document.title = 'blah blah';
      });
      
      
      • Example of the one need clean up
      useEffect(() => {
        document.title = 'blah blah';
        return cleanup () {
          // doing cleaing up here
        }
      });
      
      • the one need cleaned up will trigger the function returned by the effect
      • whenever the state / props change the affect will be clean up and then hooked again
      • By default the component will watch all props / state changed to fire affect, however this can be customized to limited the rule into some specific props / state be passing 2nd parameter into useAffect
      useEffect(() => {
        document.title = 'this is going to be render again when only props.customerId is updated';
        return cleanup () {
          //  cleaing up here will only be fired when props.customerId is changed
        }
      }, [props.customerId]);