I'm trying to update state in a higher-order component from a child. My solution is to set state to true after setting tags. useEffect runs when state is true, firstly updating state in the parent component and then updating state to false, which halts its invocation. My aforementioned solution is the only way I've managed to prevent useEffect's infinite loop.
const Student = ({
appendTags,
student: {
id: studentId,
firstName,
lastName,
pic,
email,
company,
skill,
grades,
tags: studentTags
}}) => {
const fullName = `${firstName} ${lastName}`;
const [tag, setTag] = useState('');
const [tags, setTags] = useState([]);
const [stateUpdated, setStateUpdated] = useState(false);
const [displayGrades, setDisplayGrades] = useState(false);
const onTagsSubmit = e => {
if (tag.length) {
e.preventDefault();
setTags(prevState => [...prevState, tag]);
setStateUpdated(true);
setTag('');
}
}
useEffect(() => {
if (stateUpdated) {
appendTags(studentId, tags);
setStateUpdated(false);
};
}, [stateUpdated, setStateUpdated, tags, appendTags, studentId]);