I am just diving deep into react. But the useEffect react hook still got me confused. I know that I can pass dependencies as an array to it to control rendering of the component. I have used props and local state to do and it works.
What's got me still confused is when I pass redux reducer as a dependency, it causes an infinite loop of rendering the component.
// users component
const usersComp = () => {
const users = useSelector(state => state.users);
useEffect(
// fetch users and update users state
useDispatch().dispatch(getUsers)
,[users]) // <-- causes an infinite loop!!
if(users.length){
return( users.map(user => <p>{user}</p>))
}
}
// getUsers Redux Thunk function
export async function getUsers(dispatch, getState) {
fetch(endpoint)
.then(response => response.json())
.then(users => {
dispatch({type: GET_USERS, payload: users})
}).catch(err => console.error("Error: ", err));
}
// users reducer
export default function usersReducer(state = [], action) {
switch (action.type) {
case GET_USERS : {
return [...state, action.payload]
}
}
}
From what I understand users starts off as an empty array, then gets filled with data from an API call. So useEffect should fire twice; when the component has just mounted and then when users state changes from the API call. So what's causing the infinite loop?