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()

{` import React, {useState} from 'react'; const [value, setValue] = useState(null); `}

useState()

{` import React, {useState} from 'react'; const [value, setValue] = useState({ id: 12, name: "YouName" }) `}

useState()

{` import React, {useState} from 'react'; function calculateValue() { return Math.sqrt(64); } const [value, setValue] = useState(calculateValue()); `}

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.