Understanding useEffect
Unanswered
Xander posted this in #help-forum
XanderOP
i think i fundamentally dont understand react useeffect. what is the point?
function Component() {
const [state, setState] = useState()
const somethingElse = state + 1
return <div onClick={() => setState(state + 1)}>{somethingElse}</div>
} doesn't setState cause a rerender and therefore somethingElse gets updated?21 Replies
useEffect is primarily used to run code after the component is mounted in the dom and sometimes you need to re run the code hence the dependency array telling it to re run the codefor example, dynamically setting page title
based on a state
sure you can do
document.title = smth when you call set state but useEffect is the only way to set it initiallyand since the logic is present in useEffect itself, why repeat yourself? just pass it as dependency and it will work
@@ts-ignore and since the logic is present in useEffect itself, why repeat yourself? just pass it as dependency and it will work
XanderOP
but doesn't setting any state always cause the component to rerender and therefore the effect needs to rerun?
in that case if it needs to rerender, it will need to remount, so why does it even matter what dependencies are on it?
no, not if the dependency is an empty array
useEffect(()=>{document.title = `You clicked ${count} times` }, [] )this code will only run once(twice in strict mode)
Asian black bear
I don't understand the premise of the original question. The initial snippet has no effect so I don't see why effects are being brought up.
XanderOP
I'm referring to a w3schools example
Asian black bear
That is absolutely terrible.
true
I would compute the value directly instead of state
Asian black bear
As you realized yourself, setting a state rerenders the component, thus values you can compute based on existing state values for example don't need an effect let alone a separate state variable.
Yet another example why 3rd party tutorials are abysmal and should be avoided.
XanderOP
right okay cool thank you for the explanation
this is literally the first don't lol