Updating state inside useCallback - React JS - reactjs

How can I restructure this code to allow a state update inside the useCallback function?
Here's what is executed first:
useEffect(() => {
getData();
}, [getData]); // errors if getData is left (missing dependency error)
In the getData function, I pass a state variable (lastDoc) to getSomething() as a parameter. It stores the last document/database row for pagination.
const [lastDoc, setLastDoc] = useState(null);
const getData = useCallback(async() => {
const data = await getSomething(lastDoc);
setLastDoc(data.lastDoc); // useSate function
}, [getSomething, lastDoc]);
This, at the moment, just causes an infinite loop where the getData function is re-rendered once setLastDoc updates the lastDoc variable, as getData has lastDoc as a dependency. If I remove the lastDoc dependency, I get the missing dependency error, which I understand to be an important error to listen to.

I think a null-check might be sufficient.
useEffect(() => {
if(lastDoc === null){
getData();
}
}, [getData, lastDoc]);

Related

useEffect is causing a infinite loop when updating state?

any idea how to refactor this code so I can be able to simply use firestore snapshot (Realtime data) to update the current state with those changeable data the SetState function simply update the current state with the new data but since i am calling is in useEffect it is triggering a loop can I use callback instead to work around this issue ?
const [data, setData] = useState<any>(null);
useEffect(() => {
let colRef = collection(db, 'Weeks');
const docRef = doc(colRef, context.focus as string);
const unsub = onSnapshot(docRef, (doc) => {
setData(doc.data());
if (doc.data()) {
context.SetState({ arr: doc.data()?.arr });
}
return () => unsub;
});
}, [data]);
remove data from the dependency and the infinate loop will end.
you do not use the data in the useEffect, remember to not useEffect on a state that you use its setter inside that useEffect or you will find yourself in such a situation its kinda like a recusive call without a condition to exit the loop.

useEffect dependency cause an infinite loop

function Reply({ id, user }) {
const [data, setData] = useState([]);
const [replyText, setReplyText] = useState("");
useEffect(() => {
async function fetchData() {
const response = await _axios.get("/reply/" + id);
setData(response.data);
}
fetchData();
}, [data]); <---- ** problem ** with data(dependency),
infinite request(call) fetchData()
...
}
what's the reason for infinite loop if there's a dependency.
as far as i know, when dependency(data) change, re-render.
but useEffect keep asking for data(axios.get(~~)).
if i leave a comment, i can see normally the latest comments, but the network tab(in develop tools) keeps asking for data(304 Not Modified, under image)
There's an infinite loop because that code says "If data changes, request information from the server and change data." The second half of that changes data, which triggers the first half again.
You're not using data in the callback, so it shouldn't be a dependency. Just remove it:
useEffect(() => {
async function fetchData() {
const response = await _axios.get("/reply/" + id);
setData(response.data);
}
fetchData();
}, []);
// ^^−−−−−−−−−− don't put `data` here
That gives you a blank dependency array, which will run the effect only when the component first mounts. (If you want to run it again after mount, use a different state member for that, or define fetchData outside the effect and use it both in the effect and at the other time you want to fetch data.)
Side note: Nothing in your code is handling rejections from your fetchData function, which will cause "unhandled rejection" errors. You'll want to hook up a rejection handler to report or suppress the error.
You are using setData after the response which causes the data to change and hence the useEffect(() => {<>your code<>} ,[data]) to fire again.
use useEffect(() => {<>your code<>},[]) if you want to execute the AJAX call only once after component mounting
or
use useEffect(() => {<>your code<>}) without the dependency if you want to execute the AJAX call after the component mount and after every update
Dependencies argument of useEffect is useEffect(callback, dependencies)
Let's explore side effects and runs:
Not provided: the side-effect runs after every rendering.
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Runs after EVERY rendering
});
}
An empty array []: the side-effect runs once after the initial rendering.
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Runs ONCE after initial rendering
}, []);
}
Has props or state values [prop1, prop2, ..., state1, state2]: the side-effect runs only when any dependency value changes.
import { useEffect, useState } from 'react';
function MyComponent({ prop }) {
const [state, setState] = useState('');
useEffect(() => {
// Runs ONCE after initial rendering
// and after every rendering ONLY IF `prop` or `state` changes
}, [prop, state]);
}

Why is React useState dependency empty in callback?

The dependency used in the useCallback is coming as null even though it is populated when calling it outside of the useCallback. I even tried removing the useCallback and used the data variable inside a regular function. It is still null. Any idea why this is happening?
const [data, setData] = useState(null);
useEffect(() => { //on page load
const data = fetchData();
setData(data)
}, []);
const func = useCallback(async (payload) => {
console.debug(data); //null
if (data) //call api with payload
}, [data]);
console.debug(data); //correct population of data
return <MyComponent onSubmit={func} /> //passed to and called from second child down from here
Do it like this
Pass the data as a parameter in useState to the function.Never mind i don't have data.So i used 'abc'.
useEffect(() => { //on page load
const data = 'abc';
setData(data)
func(data)
}, []);
Next step take the data as a parameter in function.
const func = (data) => {
console.log(data); //now it will have abc
};
The only way I could get this to work in all cases was to move func() down to the child...where it's used. And because data is used in both parent and children, I passed it down to the children and pushed any modifications to it back up to the parent after running func() so the modified data could be set() in the parent.

Infinite re-render in functional react component

I am trying to set the state of a variable "workspace", but when I console log the data I get an infinite loop. I am calling the axios "get" function inside of useEffect(), and console logging outside of this loop, so I don't know what is triggering all the re-renders. I have not found an answer to my specific problem in this question. Here's my code:
function WorkspaceDynamic({ match }) {
const [proposals, setProposals] = useState([{}]);
useEffect(() => {
getItems();
});
const getItems = async () => {
const proposalsList = await axios.get(
"http://localhost:5000/api/proposals"
);
setProposals(proposalsList.data);
};
const [workspace, setWorkspace] = useState({});
function findWorkspace() {
proposals.map((workspace) => {
if (workspace._id === match.params.id) {
setWorkspace(workspace);
}
});
}
Does anyone see what might be causing the re-render? Thanks!
The effect hook runs every render cycle, and one without a dependency array will execute its callback every render cycle. If the effect callback updates state, i.e. proposals, then another render cycle is enqueued, thus creating render looping.
If you want to only run effect once when the component mounts then use an empty dependency array.
useEffect(() => {
getItems();
}, []);
If you want it to only run at certain time, like if the match param updates, then include a dependency in the array.
useEffect(() => {
getItems();
}, [match]);
Your use of useEffect is not correct. If you do not include a dependency array, it gets called every time the component renders. As a result your useEffect is called which causes setProposals then it again causes useEffect to run and so on
try this
useEffect(() => {
getItems();
} , []); // an empty array means it will be called once only
I think it's the following: useEffect should have a second param [] to make sure it's executed only once. that is:
useEffect(() => {
getItems();
}, []);
otherwise setProposal will modify the state which will trigger a re-render, which will call useEffect, which will make the async call, which will setProposal, ...

React Native + Firestore infinite loop, using hooks

just starting to learn hooks here.
I am getting data from firestore and trying to set it to state using hooks. when I uncomment the line doing so, I get stuck in an infinite loop. no error, but the console goes crazy with logging the state thousands of times.
Let me know if you need more info!
function Lists(props) {
const [lists, setLists] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => {
const subscriber =
firestore().collection('users').doc(props.user).collection('lists')
.onSnapshot(QuerySnapshot => {
const items = []
QuerySnapshot.forEach(documentSnapshot => {
items.push({
...documentSnapshot.data(),
key: documentSnapshot.id,
});
//setLists(items)
setLoading(false)
console.log(lists)
})
})
// unsubscribe from firestore
return () => subscriber();
})
//rest of func..
this issue happens becauase useEffect gets called over and over again. useEffect is like componentDidMount and componentDidUpdate if you are familiar with React class components.
so whenever you set the state inside the useEffect, you trigger an update, and then, useEffect gets called again, and thus the infinite loop.
to fix this, useEffect accepts a extra argument, which is an array of dependancies, which indicates that this useEffect call should only re-executed whenever a change happens to one of its dependancies. in your case you can provide an empty array, telling react that this useEffect should only be called one time.
useEffect(() => {
const subscriber =
firestore().collection('users').doc(props.user).collection('lists')
.onSnapshot(QuerySnapshot => {
const items = []
QuerySnapshot.forEach(documentSnapshot => {
items.push({
...documentSnapshot.data(),
key: documentSnapshot.id,
});
//setLists(items)
setLoading(false)
console.log(lists)
})
})
// unsubscribe from firestore
return () => subscriber();
}, []) // <------------ the second argument we talked about

Resources