I have read in Redux docs:
The selector will be run whenever the function component renders
(unless its reference hasn’t changed since a previous render of the
component so that a cached result can be returned by the hook without
re-running the selector). useSelector() will also subscribe to the
Redux store, and run your selector whenever an action is dispatched.
Based on my understanding, selectors are said to run again whenever an action is dispatched. also, according to the documentation, they state that “The selector will be run whenever the function component renders.” If this refers to the initial re-render, then that’s correct. But if it implies running on every re-render, I believe this might not be accurate. For example, what would be the benefit of re-running selector logic if the state hasn’t changed, such as switching the website theme from light to dark? I’ve tested this scenario using the following code:
import {useState} from "react";
import CartMangment from "./cartfeatuer/CartMangment";
import UserMangment from "./userfeatuer/UserMangment";
function App()
{
const [text, setText] = useState(0);
return (
<div className="flex flex-wrap p-4">
<input type="text" onChange={(e) => setText(e.target.value)}/>
<UserMangment/>
<CartMangment/>
</div>
);
}
export const UserListAbove30Years = (state) => {
console.log("UserListAbove30Years run");
return state.user.userList.filter((user) => user.age > 30);
};
When I use setText to update the state in , causing it to re-render,all children will render also and the (console log "UserListAbove30Years run"
) does not printed on console, despite it returns a new reference each time due to lack of memoization. Therefore, I’m puzzled by the statement in the documentation: “The selector will be run whenever the function component renders.”
What does ‘The selector will be run whenever the function component renders’ mean in the Redux docs? Please clarify my confusion as mentioned in the question.
This a bit far away from your answer, but I suggest you to use useContext hook, since redux is hard to understand and complex to use.
if your project is not so big, context will be ideal solution.
1