I have these routers
function Rutas(){
<Provider store={store}>
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</Router>
</Provider>
}
This is my Sidebar
function Home(){
return (
<>
<NavLink to="/home">Home</NavLink>
<NavLink to="/about">About</NavLink>
</>
)
}
And this is the Home component
function Home(){
const dispatch = useDispatch();
const homeData = useSelector((data) => data.homeData);
React.useEffect(() => dispatch(getHomeDataAction),[dispatch])
return (
<>
{
homeData.map((res) => <span>{res.title}</span>)
}
</>
)
}
And this is the About component
function About(){
const dispatch = useDispatch();
const aboutData = useSelector((data) => data.aboutData);
React.useEffect(() => dispatch(getAboutDataAction),[dispatch])
return (
<>
{
aboutData.map((res) => <span>{res.title}</span>)
}
</>
)
}
On page load for the first time the Home component rendered, that's okay, when i change route to About component it's rendered too and this it's okay, but the problem it's when i change route again to the Home component it's rendered again and it call useEffect and dispatch again, I WANT TO PREVENT TO DISPATCH AGAIN WHEN THE ROUTE CHANGE BECOUSE I HAVE A LOT OF DATA AND IT TAKE A WHILE TO RENDERED AGAIN THE DATA FROM USESELECTOR AND THE UI IT'S SO SLOW.
Please tell me some solution or recommendations.
Thanks ☺
You could somehow memorize does getHomeDataAction action was dispatched or not.
const loadedData = useSelector((data) => data.homeData.loaded);
React.useEffect(() => {
if (!loadedData) {
dispatch(getHomeDataAction)
}
},[dispatch, loadedData])
All in all calling the getHomeDataAction action conditionally could help.
Apart from these changes you should extend your reducer.
After dispatching getHomeDataAction action the first time the value of the loaded property should be turned to true.