React Builtin Hooks

React Builtin Hooks

What is a State?

  • State is something which holds the info or details about a Component's State at a TIME
  • It can change over time.
  • Whenever the state changes the COMPONENT attached to it re-renders

useState()

  • useState hooks allows to have state variable inside a FUNCTIONAL COMPONENT
  • useState ENCAPSULATES only a single value
  • For mulatiple values you may need to call multiple useState's
  • useState arguments
    • Initialization of a state variable
    • Passing function as initial value - to calculate an initial value
  • Managing multiple states
    • Multi-variable's
    • Object as value

Side Effects

  • Something which is outside the scope of REACT
    • Calling AJAX requests
    • Calling Web API stuffs (document.get...)
    • localStorage etc...
    • setTimeout, setInterval
  • Everything which is not part of React Library
  • Fun Fact - What happens if you call setTimeout without any arguments
    • Executes outside the execution queue

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect" }) `}

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect" }) ← No Arguments means this will be called each time this component re-renders `}

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect" }, []) ← An empty array as an argument will run the effect once the component is mounted `}

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect" }, [prop1]) ← We can pass value `}

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect" }, [prop1, state1]) ← Actually we can pass multiple-values `}

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect" }, [prop1, state1]) ← This is called dependency list `}

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect" }, [prop1, state1]) ← Effect will run whenever any of the values on dependency list changes `}

useEffect

{` useEffect(() => { document.title = "Hey There, I'm from useEffect"; return () => { // Clean Up function 🧹 } }, [prop1, state1]); `}
  • You can do removeListeners, unsubscribes, reset layouts etc
  • This will be called by default when component unmouts.