componentwillmount componentwillunmount react hooks code example

Example 1: replace componentwillmount with hooks

useEffect(() => {
	//will be called on every load
})

useEffect(() => {
	//will be called on component mount
  window.addEventListener('mousemove', () => {});

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', () => {})
  }
}, []) // <---- empty array at end will cause to only run on first load

Example 2: componentwillreceiveprops hooks

const { useState, useEffect, useMemo } = React;

function App() {
  const [count, setCount] = useState(50);

  useEffect(() => {
    setTimeout(() => {
      setCount(150);
    }, 2000);
  }, []);

  return <DisplayCount count={count} />;
}

function DisplayCount(props) {
  const count = useMemo(() => props.count > 100 ? 100 : props.count, [props.count]);

  return <div> {count} </div>;
}

ReactDOM.render(<App />, document.getElementById("root"));

Tags:

Misc Example