patternjavascriptreactCritical
componentDidMount equivalent on a React function/Hooks component?
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
For
For
So in this situation, you need to pass your dependency into this array. Let's assume you have a state like this
And whenever count increases you want to re-render your function component. Then your
This way whenever your count updates your component will re-render. Hopefully this will help a bit.
For
componentDidMountuseEffect(() => {
// Your code here
}, []);For
componentDidUpdateuseEffect(() => {
// Your code here
}, [yourDependency]);For
componentWillUnmountuseEffect(() => {
// 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 thisuseEffect(() => {
// {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.