I don't think I've ever received this error before:
The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant.
I've done axios requests in useEffect()
100 times, using useEffect()
in a similar manner to componentDidMount()
, but this is the first time that I've used a reusable function with async
/await
, and resolved the data back to the useEffect()
. Other people online are doing this exact same thing in their tutorials, but they never mentioned this error.
const [tableData, setTableData] = useState([])
useEffect(() => {
const data = async() => {
const dataArr = await getPagList('tags', 1, 25)
console.log("Data received: ", dataArr)
if(dataArr.length > 0) {
setTableData(dataArr)
}
}
data()
}, [])
I believe, it's complaining about the empty array I'm feeding useEffect()
as the 2nd parameter. However, that empty array isn't changing... Right? I tried googling it, but the solutions I found for this error were what I'm already doing. None of the examples were using async
/await
.
I have also tried this, with no success:
useEffect(() => {
setData()
}, [])
const setData = () => {
const data = async() => {
const dataArr = await getPagList('tags', 1, 25)
console.log("Data received: ", dataArr)
if(dataArr.length > 0) {
setTableData(dataArr)
}
// TODO Properly handle this data now that I'm getting it in. It's only 9 records though.
}
data()
}
Am I not exiting the useEffect properly or something? Anyway, thanks guys.
Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.
Side Effect Runs After Every Render The first is the default case. If you do not pass the dependency array to the useEffect hook, the callback function executes on every render. Thus React will run the side effect defined in it after every render. useEffect(() => { // Side Effect });
Anatomy of the useEffect hook The return function is the cleanup function, or when the user leaves the page and the component will unmount. The array is the last part, and it is where you put the states that will update throughout the component's lifecycle.
Use the useEffect hook to listen for state changes in React. You can add the state variables you want to track to the hook's dependencies array and the logic in your useEffect hook will run every time the state variables change.
If you have a
useEffect(() => {}, itemArray)
and you modify itemArray, you will get this error. this is probably just a typo. I did this when I had a list of items I was using from state. It didn't catch it because it was an array. You need [] around the itemArray.
useEffect(() => {}, [itemArray])
The real issue is that your dependency array changed size, not that you added another item to your array. fix this typo and you should be fine.
You can try this
useEffect(() => {
}, [itemList])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With