componentDidMount equivalent on a React function/Hooks component?

Are there ways to simulate componentDidMount in React functional components via hooks?

Answers:

Answer

For the stable version of hooks (React Version 16.8.0+)

For componentDidMount

useEffect(() => {
    // Your code here
  }, []);

For componentDidUpdate

useEffect(() => {
    // Your code here
  }, [yourDependency]);

For componentWillUnmount

useEffect(() => {
    // componentWillUnmount
    return () => {
       // Your code here
    }
  }, [yourDependency]);

So in this situation, you need to pass your dependency into this array. Let's assume you have a state like this

const [count, setCount] = useState(0);

And whenever count increases you want to re-render your function component. Then your useEffect should look like this

useEffect(() => {
    // <div>{count}</div>
  }, [count]);

This way whenever your count updates your component will re-render. Hopefully this will help a bit.

Answer

Yes, life cycle methods like componentDidMount are only available in class components.

Class components should not be considered deprecated, even after the advent of hooks, they will remain a substantial part of React.

Answer

You want to use useEffect(), which, depending on how you use the function, can act just like componentDidMount().

Eg. you could use a custom loaded state property which is initially set to false, and switch it to true on render, and only fire the effect when this value changes.

Documentation

Answer

There's no componentDidMount on functional components, but React Hooks provide a way you can emulate the behavior by using the useEffect hook.

Pass an empty array as the second argument to useEffect() to run only the callback on mount only.

Please read the documentation on useEffect.

function ComponentDidMount() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log('componentDidMount');
  }, []);

  return (
    <div>
      <p>componentDidMount: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <ComponentDidMount />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/[email protected].0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.