ReactJS

From official first generated readme

Setup

Node

npm install -g create-react-app
npx create-react-app my-app
cd my-app

CDN

<script src='https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js'></script>

Component Life Cycle (pre 16.3, 16.3)

  • Creation
    1. constructor()
    2. componentWillMount() – deprecated
    3. render()
    4. create all direct-child component
    5. componentDidMount()
  • Re-rendering due to re-rendering parent
    1. componentWillReceiveProps() – deprecated
    2. shouldComponentUpdate()
    3. componentWillUpdate()
    4. render()
    5. send new props to all direct child components
    6. componentDidUpdate()
  • Re-rendering due to this.setState()
    1. shouldComponentUpdate()
    2. componentWillUpdate()
    3. render()
    4. send new props to all direct child components
    5. componentDidUpdate()
  • Re-rendering due to this.forceUpdate()
    1. render()
    2. send new props to all direct child components
    3. componentDidUpdate()
  • Re-rendering due to catching error
    1. parent render()
    2. send new props to all direct child component
    3. error thrown in any life-cycle method
    4. parent componentDidCatch() - store error data

Using react element ref (more)

class RefComponent extends React.Component {
  onFocus() {
    this.myInput.setAttribute("class", "highlight");
  }

  onBlur() {
    this.myInput.setAttribute("class", "");
  }

  render() {
    return (
      <div>
        <input
          ref={input => {
            this.myInput = input;
          }}
          onFocus={this.onFocus.bind(this)}
          onBlur={this.onBlur.bind(this)}
        />
      </div>
    );
  }
}

JSX

JSX = Script to render component

Multiple tag component

function renderSomething(){
  return <>
    <div>div-1</div>
    <div>div-2</div>
  </>

}

Hook

Second argument of useEffect is dependency option

  • none: run on every render
  • []: run once
  • [a,b]: run when a or b change

Run once example

useEffect(() => {
  fetchSettings().then((settings) => {
    setSettings(settings);
  });
}, []);