First of all, there is no need to call setArray([]);
when your ultimate goal is to change the value of the array to the value
that is passed down from your function.
The reason why it probably doesn't update from time to time is because the Virtual DOM hasn't seen any changes at all or you're not iterating over them correctly.
If you're changing the values of an array using useState
and looping over them and returning components, make sure to always set the key
property of your elements, which should be set to a unique identifier, so the Virtual DOM can function properly. For more information, please read the React documentation:
https://reactjs.org/docs/lists-and-keys.html#keys
To answer your question in regards to clearing arrays: you can clear arrays by setting the variable to null
.
let exampleArray = ['a', 'b', 'c'];
console.log(exampleArray);
exampleArray = null;
console.log(exampleArray);
https://jsfiddle.net/mgfq75e2/
Do note that if you're using the useState
hook, it might take a couple of cycles before the changes are visible in your rendered output since it is executed asynchronously.
If you want to know when the state is actually updated, you could use the useEffect
hook and pass your (array) variable so it fires when the state is updated:
import React, {useState, useEffect} from 'react';
const Example = () => {
const [exampleArray, setExampleArray] = useState(['a', 'b', 'c']);
const handleClick = (e) => {
setExampleArray(null);
};
useEffect(() => {
console.log(exampleArray);
}, [exampleArray]);
return (
<button onClick={handleClick}>Test</button>
);
};
export default Example;
https://codesandbox.io/s/eloquent-faraday-n429p?file=/src/App.js
For more information, please take a look at the React docs:
https://reactjs.org/docs/hooks-state.html