It's generally acceptable to update state within a useEffect hook, provided you are aware of how React's rendering process works and you avoid creating a situation that leads to an infinite loop or unexpected behavior.
In your case, you're modifying the state of annotationVisible within a useEffect triggered by changes to annotationVisible. This can potentially lead to an infinite loop because updating annotationVisible will cause the effect to re-run, and if within the effect you change annotationVisible again, it will trigger another render.
Here is the revised code snippet, incorporating best practices to prevent potential infinite loops and ensuring clean-up is handled correctly:
import React, { useEffect, useState, ChangeEvent } from 'react';
const Highlight = ({ children, id, annotation }: { children: React.ReactNode, id: string, annotation: string }) => {
const [isVisible, setIsVisible] = useState(false);
const [annotationVisible, setAnnotationVisible] = useState(false);
const [annotationKey, setAnnotationKey] = useState(id); // Assuming `id` as the initial key
const [annotDict, setAnnotDict] = useState<{ [key: string]: any }>({});
const [preprocessedMessage, setPreprocessedMessage] = useState("your initial message");
const sortAnnotDict = (dict: { [key: string]: any }) => {
// your sorting logic
return dict;
}
const insertHighlightMarkers = (text: string, dict: { [key: string]: any }) => {
// your highlight insertion logic
return text;
}
const handleMouseEnter = () => {
const selection = window.getSelection();
if (selection && selection.toString().length > 0) {
setIsVisible(false);
} else {
setIsVisible(true);
}
};
useEffect(() => {
const targetElement = document.getElementById(annotationKey);
let inputBox = document.createElement('input')
let tooltip = document.getElementById('tool' + annotationKey)
if (annotationVisible) {
inputBox.type = 'text';
inputBox.style.fontSize = "14px";
inputBox.style.height = "2rem";
inputBox.style.width = "max-content";
inputBox.style.padding = "0.5rem";
inputBox.style.lineHeight = "150%";
inputBox.style.fontFamily = "Arial, sans-serif";
inputBox.style.font = "Arial, sans-serif";
inputBox.style.minHeight = "1.6rem";
inputBox.style.maxHeight = "3.2rem";
inputBox.style.textOverflow = "ellipsis";
inputBox.style.position = "absolute";
inputBox.style.marginRight = '5px';
inputBox.style.top = '50%'
inputBox.style.transform = 'translateY(-50%)'
inputBox.style.zIndex = '99999999999999';
inputBox.className = [
'w-auto',
"self-center",
"rounded",
"border",
"bg-danger-50",
"text-lg",
"w-full",
"border-secondary-400",
"transition ease-in-out",
"focus:border-secondary-700",
"focus:outline-none",
"placeholder-base",
"hover:none"
].join(" ")
inputBox.ariaHidden = 'true'
inputBox.placeholder = 'Add annotation . . .';
inputBox.maxLength = 125;
console.log("ADDED", inputBox)
targetElement?.appendChild(inputBox)
inputBox.onkeydown = (e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
console.log(annotationKey);
console.log('text', preprocessedMessage);
setAnnotDict(prevDict => ({
...prevDict,
[annotationKey]: { ...prevDict[annotationKey], annotation: target.value }
}));
let ad = { ...annotDict, [annotationKey]: { ...annotDict[annotationKey], annotation: target.value } };
ad = sortAnnotDict(ad);
setAnnotDict(ad); // correct update of state
inputBox.textContent = "";
if (tooltip) { tooltip.textContent = ""; }
target.value = '';
setPreprocessedMessage(insertHighlightMarkers(preprocessedMessage, annotDict)) //Update the preprocessed message with highlights
setAnnotationVisible(false);
setAnnotationKey('');
}
}
return () => {
console.log("RETURN REMOVAL")
if (targetElement && targetElement.contains(inputBox)) {
targetElement.removeChild(inputBox);
console.log('REMOVED2', inputBox)
}
};
} else {
targetElement?.removeChild(inputBox);
}
}, [annotationVisible, annotationKey, annotDict, preprocessedMessage]);
return (
<span
id={id}
className="highlight"
onMouseEnter={handleMouseEnter}
onMouseLeave={() => setIsVisible(false)}
>
{children}
{isVisible && (
<span id={'tool' + id} className="tooltip" aria-hidden="true">
{annotation}
</span>
)}
</span>
);
};
export default Highlight;
Summary of Key Changes:
1. useEffect Dependency Handling:
- Added the necessary dependencies (
annotationKey, annotDict, preprocessedMessage) to the useEffect dependency array to prevent unexpected behavior.
2. State Update Handling:
- Ensured
annotDict is updated correctly.
- Added
inputBox.textContent = ""; before resetting the input box to ensure previous content is cleared.
3. Clean-Up in useEffect:
- Ensured clean-up is handled correctly upon unmounting the component or when the dependencies change.
Feel free to adjust the code as per your specific requirements and additional functionalities.