You may have encountered a situation where you want to update a state variable inside a component function, but you can't because it triggers an infinite loop of re-rendering. You may also think of using useRef, but the React documentation says "Do not write or read ref.current during rendering." So what can you do? Here's a trick: if you use an external variable, you can write and read it during render. But be careful, it could cause side effects or unexpected behavior. Always make sure you have a clear logic for when and how to update your external variable.
let globalVar = 'default value';
export default function App() {
//somethings happen
const example = false;
example ? globalVar : (globalVar = 'New value');
//setState make a infinity loop here
return (
<div>
<h1>Hello!</h1>
<p>{globalVar}</p>
</div>
);
}
Top comments (0)