I've been trying to add optional JSX based on the circumstance, so I have initialized them to null and updated them once the time is right so they contain JSX.
//initialize potentially unused parts
let monitor = null;
let keyboard = null;
...
Later in my JSX I use these to only display information if it exists.
{monitor}
{keyboard}
I did some research and found that my states were not updating because useState is asynchronous, so I set the useEffect hook in attempt to update these variables when state is finally updated.
const [monitorState, setMonitorState] = useState(0);
const [keyboardState, setKeyboardState] = useState(0);
useEffect(() => {
monitor = (
<li>
<span className="bold">Monitor: </span>
{monitorState.title}}
<span className="right">${monitorState.price}</span>
</li>
);
}, [monitorState]);
const handler = (item) => {
if (item.type === "monitor") {
setMonitorState(item);
}
...
}
This handler is called when an add button is clicked in a modal component:
<a
onClick={() => props.handler(item)}
href="#!"
className="modal-close btn waves-light waves-effect grey darken-3
white-text modal-item-add">
Add
</a>
However, I get an error:
Assignments to the 'monitor' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect.
I'm confused how exactly useRef will solve this problem and how to even implement that given this issue. I've looked at other threads but none of them have been done updating a JSX variable.