In the following example, I used history to redirect some link.
const history = useHistory()
useEffect(() => {
history.push(`/my/link`)
}, [])
Then react complains a missing dependency history. I do not understand why history can be a dependency here. It is not a state variable or from props.
If I add history to the dependency array, will it cause an infinite call of useEffect. Because history is changed when history.push(/my/link) happens.
const history = useHistory()
useEffect(() => {
history.push(`/my/link`)
}, [history])
Is my understanding correct here?
While history is not directly a state variable (from your component's perspective) nor is it a prop, it is the output of a hook and therefore likely held in state within the hook. Also the exhaustive dependency rule does not just apply to state and prop variables but to any variable whose value might change.
If you want to avoid that infinite rerender, you can just put history.push in your dependency array or just take push out of history and use it directly and put push in the dependency array. Examples:
const history = useHistory();
React.useEffect(() => {
history.push("/my/link");
}, [history.push]);
const { push } = useHistory();
React.useEffect(() => {
push("/my/link");
}, [push]);
Alternatively, for this specific example, you might consider using the <Redirect> component instead of history.push.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With