componentDidMount alternate in hooks code example

Example 1: alternative for componentdidmount

import React, { useEffect } from 'react'const SampleComponent = () => {  useEffect(() => {    // code to run on component mount  }, [])return (
foo
)}export SampleComponent

Example 2: componentdidmount functional hook

import { useState, useEffect } from 'react';

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowDimensions;
}

Tags:

Misc Example