Videos
What is the useEffect hook used for in React?
Why is the dependency array important in useEffect?
What happens if you don’t pass a dependency array to useEffect?
I just read that a UseEffect without a 2nd argument re-runs on every render or re-render of the component.
This defeats the whole purpose of the UseEffect and would be equivalent to just having an anonymous function or a function call (or simply running code) from within the body of the component, which would run each time the component re-renders.
Is my logic correct? or are the 2 still different?
html elements, so it was a simple solution to just do a UE on the parent component that ran the script on re-renders.
useEffect hook is used to execute functionality according to data change / onload. It can't receive parameters, If you want to use the id of your current render in your useEffect you should send him as prop.
useEffect hook doesn't take a parameter. You have to pass the parameter in the component.
const Component = ({ id }) => {
useEffect(() => {
axios
.get(`http://localhost:4000/getTopic/${id}`)
.then((post) => {
console.log('--------post.data', post.data.description);
})
.catch((err) => {
console.log('--------err', err);
})
})
return (
// your render
)
}
The first will run the effect on mount and whenever the state changes. The clean up will be called on state change and on unmount.
The second will only run the effect once on mount and the clean up will only get called on unmount.
The last will run the effect on mount and whenever the isOn state changes. The clean up will be called when isOn changes and on unmount.
In your examples, the first and last examples will behave the same because the only state that will change is isOn. If the first example had more state, that effect would also refire if the other state were to change.
I guess I should also add is that the order of things would be like: mount: -> run effect, state change: run clean up -> run effect, unmount -> run clean up.
There are two things that you need to note while using useEffect
Not passing the second argument
In the above case useEffect will clean up the previous effect if the return function was specified and run a new effect on each render of the component
Passing the second argument as empty array
In the above case the effect will be run on initial render and on unmount the effect will be cleared with the return function was specified
Passing the second argument as array of values
In the above case effect will run on initial render and on change of any of the parameters specified within the array. The clean method returned from effect is run before new effect is created