I have this piece of react code:
import React, {useEffect} from "react";
import "./styles.css";
export default function App() {
let x ={ x1: []};
useEffect(() => {
x.x1.push("hi")
})
console.log(x)
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
I want to know why the console always prints the value as an empty array for my key x1 in object x. What am I missing here?
Your component only render once (no state or props change)
Even if your state rerender as if you force it, the let x ={ x1: []};
will always be re-initialised for every new render.
If you want to see your x
variable is updated, try to use useRef
instead, and make your component re-render to see it inside useEffect
:
function App() {
const [state, setState] = React.useState();
const x = React.useRef({ x1: [] });
React.useEffect(() => {
x.current.x1.push("hi");
setState(1);
}, []);
console.log(x.current);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>