I am pretty new to react-hooks and I have yet to discover its real super powers. I want to ask if I am breaking anything if I do the sample code below.
let somevariable= [];
const SomeComponent = () => {
const [state, setState] = useState({});
useEffect(()=>{
fetch('http://insert-api/state')
.then(response => response.json())
.then(data => setState({ data }));
},[])
useEffect(()=>{
//update `somevariable` whenever the state changes
somevariable = state.something
},[state])
const clickMe = () => {
console.log(somevariable)
//do something to somevariable
}
return (
<button onClick={clickMe}>Click Me </button>
)
}
Instead of putting somevariablein the state I put it outside to make it kind of global. I did this because when I put somevariable in its own state and set its value in the useEffect it results to endless loop but this one does not, so this is like my workaround. A lot of my functions rely on somevariable that's why it's important for me to know if this approach is alright or not.
PS. I don't know if it's alright to ask this here so please tell me if it's not and I will take it down. Thanks.
Top comments (1)
When you put the
somevariableoutside of React's control, changing the value ofsomevariablewould not trigger components depending on that value to re-render.e.g.)
You can fork and try it yourself

You can see that
Childthat depends on the change ofsomevariabledoes NOT render, assomevariableis not a state tracked by React.The demo below doesn't render the
Childcomponent (with<h1>{somevariable}</h1>element)Can you post a runnable code (possibly forking the sandbox) that causes the infinite loop?