Blog.

Mudando para React Hooks

Cover Image for Mudando para React Hooks

Os três mais comuns ciclos de vida de um componente no React, mas agora usando Hooks, apenas um simples "cheat-shee"

componentDidMount

before

class Example extends React.Component {
  componentDidMount() {
    console.log('I am mounted!')
  }
  render() {
    return null
  }
}

after

function Example() {
  useEffect(() => {
    console.log('mounted')
  }, [])
}

componentDidUpdate

before

class Example extends React.Component {
  componentDidMount() {
    console.log('mounted or updated')
  }
}

also

class Example extends React.Component {
  componentDidUpdate() {
    console.log('mounted or updated')
  }
}

after

function Example() {
  useEffect(() => {
    console.log('mounted or updated')
  })
}

componentWillUnmount

before

class Example extends React.Component {
  componentWillUnmount() {
    console.log('will unmount')
  }
}

after

function Example() {
  useEffect(() => {
    return () => {
      console.log('will unmount')
    }
  }, [])
}