Reputation: 14831
I am working on a React JS application. I am using functional components and react hooks in my application. I am figuring out the componentDidMount counterpart in hooks.
This is my code
const Items = () => {
useEffect(() => {
fetchItems(); //this function is being called whenever the state is updated. I am looking for componentDidMount counterpart
return () => {
//clean up
}
})
return (
//return the view component
)
}
As you can see in the component, I want to move the function call into componentDidMount counterpart for hooks. How can I do that?
Upvotes: 0
Views: 75
Reputation: 153
useEffect vs Component life cycle methods
const [data, setData]=useState("")
const [inpVal, setInpVal]= useState("")
useEffect(() => {
fetchItems(inpVal);
},[]); //if you put an empty array then it will act as componentdidmount
useEffect(() => {
fetchItems(inpVal);
},[inpVal]); //if you put an inpVal in array then it will act as componentDidUpdate which means when ever the inpVal change useeffect will run
Upvotes: 2
Reputation: 2317
You should simply add an empty array of dependencies to your useEffect
call.
const Items = () => {
useEffect(() => {
fetchItems(); //this function is being called whenever the state is updated. I am looking for componentDidMount counterpart
return () => {
//clean up
}
}, []) // <-- add this
return (
//return the view component
)
}
Upvotes: 2