HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

componentDidMount equivalent on a React function/Hooks component?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
hooksfunctioncomponentreactcomponentdidmountequivalent

Problem

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

Solution

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(() => {
  // {count}
}, [count]);


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

Code Snippets

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

Context

Stack Overflow Q#53945763, score: 664

Revisions (0)

No revisions yet.