Quick React Part 2

Posted on October 2, 2021
Tags: javascript

1 Intro

Component goes through 3 phases. * Function Body * useEffect * return()

In each phase code is ran by the order they are declared. (eg. if we have 2 useEffect() on line 2 and line 5, the first one at line 2 will always run first)

const App = () => {
  // function body START
  const a = 3;
  const b = new TextEncoder()
  // function body END
  
  // useEffect START
  useEffect(()=>{
      const c = 6;
  },[])
  // useEffect END

  //return() START
  return(<div>my stuff</div>)

  //return() END
}

2 Composition/Extending Components

function Dialog(props) {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        {props.title}
      </h1>
      <p className="Dialog-message">
        {props.message}
      </p>
    </FancyBorder>
  );
}

function WelcomeDialog() {
  return (
    <Dialog
      title="Welcome"
      message="Thank you for visiting our spacecraft!" />
  );
}

3 SSR and window object

PROBLEM: The below will fail because the page is rendered on the server, meaning there is no window object.

const bleh:NextPage = () => {
  return(
    <div>{window.clientInformation}</div>
  )

}

SOLUTION: Use-effect is clientside render

3.1 Convert JS Api objects to React usable hooks

mozilla web api has a list of API’s for vanilla JS. Typically you call a global object then use the object’s function to use the API.

Ideally in functional React, we don’t like to call global variables so we use hooks.

const bleh:NextPage = () => {
    const bleh = new TextEncoder() //BAD
    useEffect(()=>{
    },[])
    return(<div>
        {bleh && console.log(bleh.encode("a"))}
        </div>)
}

the new is a side-effect. Remember to only put side-effects in hooks.

const bleh:NextPage = () => {
    const bleh = new TextEncoder() //BAD
    useEffect(()=>{
    },[])
    return(<div>
        {bleh && console.log(bleh.encode("a"))}
        </div>)
}

4 Hooks

https://www.netlify.com/blog/2019/03/11/deep-dive-how-do-react-hooks-really-work/

// Example 0
function useState(initialValue) {
  var _val = initialValue // _val is a local variable created by useState
  function state() {
    // state is an inner function, a closure
    return _val // state() uses _val, declared by parent funciton
  }
  function setState(newVal) {
    // same
    _val = newVal // setting _val without exposing _val
  }
  return [state, setState] // exposing functions for external use
}
var [foo, setFoo] = useState(0) // using array destructuring
console.log(foo()) // logs 0 - the initialValue we gave
setFoo(1) // sets _val inside useState's scope
console.log(foo()) // logs 1 - new initialValue, despite exact same call

What this says is _val