I am trying to create a hook that extracts some redux related actions that i will reuse in many components. the hook includes dispatching and reading selectors.
The problem is that that the selector doesn’t update correctly, the redux dev tool shows an array with a single element but when logging the selector the same array is empty.
hook code :
function useManager() {
const [isManaged, setManaged] = useState(false)
const dispatch = useAppDispatch() // just a re-export of redux's useDispatch
let stackArray = useAppSelector(stack) // stack is a defined selector (state => state.stack)
const checkArrayLength = () => {
return stack.length > 0;
}
const setManagedState = useCallback(
() => {
if(checkArrayLength()){
console.log(stack.length) <== will always log 0
setManaged(true)
}
},
[],
)
return {
setManagedState,
isManaged,
}
}
in a different component i call this hook :
function Component(props) {
const { setManagedState, isManaged } = useManager();
//...
/ * I use useSelector inside this component to update the store stack */
//...
setManagedState() // will log 0, even if i push to the stack and i can see the changes in the redux tools.
}
is there something i should check ?, i tried to check the equality Function of useSelector (second arg), but i didn’t understand the issue from there.
I am relatively new to functional components and hooks, so i am probably missing something (maybe related to rendering cycles needed for the useSelector hook to update).