React

Lifecycle & hooks

Ancien cycle de vie

Ancien cycle de vie

Nouveau cycle de vie

Hooks =

Fonctions "useXXX",

à utiliser dans un Function component,

réalisant des effets de bord avec React

State + setState

useState

function Counter() {
    const [count, setCount] = useState(0)
    return (
      <div>
        Count: {count}
        <button onClick={() => setCount(count + 1)}>Add</button>
      </div>
    )
}

Le setter renvoyé par useState peut aussi prendre une fonction, comme setState :

function Counter() {
    const [count, setCount] = useState(0)
    return (
      <div>
        Count: {count}
        <button onClick={() => setCount(c => c + 1)}>Add</button>
      </div>
    )
}

componentDidMount / componentDidUpdate / componentWillUnmount

useEffect

componentDidMount

function Counter() {
    const [count, setCount] = useState(0)

    useEffect(() => console.log('mounted'), [])

    return (
      <div>
        Count: {count}
        <button onClick={() => setCount(count + 1)}>Add</button>
      </div>
    )
}

componentDidMount + componentDidUpdate

function Counter() {
    const [count, setCount] = useState(0)

    useEffect(() => console.log('mounted or updated'))

    return (
      <div>
        Count: {count}
        <button onClick={() => setCount(count + 1)}>Add</button>
      </div>
    )
}

componentWillUnmount

function Counter() {
    const [count, setCount] = useState(0)

    useEffect(() => () => console.log('will unmount'), [])

    return (
      <div>
        Count: {count}
        <button onClick={() => setCount(count + 1)}>Add</button>
      </div>
    )
}

componentDidMount + componentWillUnmount

function Counter() {
    const [count, setCount] = useState(0)

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

    return (
      <div>
        Count: {count}
        <button onClick={() => setCount(count + 1)}>Add</button>
      </div>
    )
}

shouldComponentUpdate

React.memo

const Button = React.memo(props => (
  <button class="unboutonquilestbeau" {...props} />
))

Class property

(exemple : timeout d'un setTimeout)

ou Ref d'un élément JSX

useRef

ReactLifecycle & hooks

By godefroy_dc

ReactLifecycle & hooks

  • 33