The array in the following code is not updating properly.
The following is the code,
const { useState, useRef, useEffect } = React;
/*export default*/ function App() {
const [array, setarray] = useState([]);
const Add = () => {
console.log(one.current.value);
setarray((e) => {
return [one.current.value, ...e];
});
// Stack Snippets can't use localStorage, but you don't need it
// to show this problem
// localStorage.setItem("notes", array);
console.log("after adding the value -> ", array);
};
const one = useRef(null);
return (
// <> No need for this fragment, and the version of Babel here on
// SO is so shockingly outdated it doesn't understand the short form
<div className="App">
<h1>Hello CodeSandbox</h1>
<div className="align">
<input ref={one} />
<br />
<br />
<button onClick={Add}>Add</button>
</div>
<div className="align"></div>
</div>
// </>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
When I am clicking the Add
button then the array is not updating, moreover, the array is updating for the first element when I am clicking the second time.
And the second is updating after the third click.
What is wrong here? Following is the code sandbox link.
https://codesandbox.io/s/silly-neumann-b0foos?file=/src/styles.css