I am using useReducerand context API to manage state. Let us say I have my state with the shape { page: 0, articles: [] } and I have useEffect hook as shown below.
useEffect(() => {
// Fetch some data and dispatch an action to update state
}, [state.page])
I can’t pass state as a dependency to useEffect because it will trigger an infinite loop but I want the effect to be invoked whenever page changes . Is what I have done above recommended? Passing page which is a field of the state object as a dependency . I have not seen anybody do that before. What is quite familiar to me is declaring something like const[page, setPage] = useState(0); and then passing page as dependency.
I dont see why it wouldn’t work, if state.page is just going to be a number it should run every time that number changes, changing page inside state should still render the page
If what you want is useEffect to run, after every update (only you can decide this, based on where the component is), then do not include a dependency array. This is the default behaviour.
Otherwise, if you are specifically interested in the state.page value causing the update, then what you have is correct, and recommended.
it will only run when state.page is changed if thats what you mean, but i would still recommend that you do it the above way that you mentioned when using useState()
Sure thanks @Sky020 . It works but I just wanted to be sure I am doing the right thing. I want the effect to run whenever the page changes so as to make an API call. To be honest the most common approach I have seen is declaring the state like const[page, setPage] = useState(0); and passing page but if my approach isn’t anti-pattern then perhaps I will have to go with it.
@biscuitmanz. I have decided to use useReducer because I want to have groups of state in separate state objects based on how related they are. For this particular one page and articles need to be together in an object like {page: 0, articles: []}.
@nibble keep in mind that if you wanted to use articles which is an array on useEffect you would have to use length so when articles are added or removed useEffect knows that the array is being changed.