I writing a simple React application with two components assigned to two urls:
App.tsx
-- foo.tsx it's url is "/foo"
-- bar.tsx it's url is "/bar"
In App.tsx, i have a navigator use useHistory.push to allow user jump between "/foo" and "/bar". user's name will be capture here and store in a Redux state as well.
In foo.tsx and bar.tsx, they're petty much same but loading different type of data from API. the code structure like:
const user = useSelector((state: RootState) => state.user)
useEffect(() => {
const api = new Api();
async function getData() {
const foo: any = await api.getFoo(user.foo)
dispatch(setFooData(foo))
}
}, [user.name])
What i had observed:
- when i first time accessed /foo, the foo page loaded all component and ran useEffect once at last, this process which is the design by the react Hook in the doc i'd read.
- I continue clicked the foo tab (useHistory.push("/foo")),nothing on the page changed, which mean the useEffect didn't be invoked since it's dependence (user.name in this case) didn't change.
- I dispatched a new value to user.foo, i saw the useEffect was invoked as expecting.
- when i jumped to the "/bar" and above processes happened similary for querying data of bar back.
- at this point, I saw data of foo and bar were in the Redux state because i uses useHistory.push() to keep the session (if i understanding correctlu). the purpose to do so because i'd like to have a cross check on both data of foo and bar in either /foo or /bar pages.
- however, when i jumped back to /foo from /bar, the useEffect had been invoked even though the value of user.name stayed same. it's like useEffect ignored the dependence and reckoned this time was a band new request and ran itself.
- I checked all state in Redux store didn't change when i jumped back. one thing i can reckon is that useHistory.push led the browser back to /foo, and
const user = useSelector((state: RootState) => state.user)ran again, useEffect lost the pervious dependence to compare so dependence was ignored.
Or, useHistory.push just works in such way, when a url push into history, it will make useEffect run at once no matter how.
I'm asking this question because i did remembered the useEffect wont be invoked when i jump back from another url, but back to that time i just started use react and not sure how i did that, and the git history had been overwhelmed by my numerous commits :(
To sum up, what I want to do is: when I access /foo, all data load, and redux state all set; same process when I access another url /bar. the useEffect doesn't been invoked when i back to /foo from /bar, unless i dispatch a new user.name. it's intent to reduce the requests to API since i had already use Redux store to manage the data for user. An other reason is that i get to figure out my understanding on useHistory, useEffect and Redux is correct.
Thanks!