Accepted answer

It's not accurate to console.log fruits because the reference to fruits is still referring to the fruits you had before you called setFruits.

If we console.log newFruits, which has the change, it would be more accurate of what is happening.

EDIT: It's probably better to useEffect as what @Atul suggested though.

It sometimes helps to visualize how this is done in old React classes. In old React classes the equivalent of this is this (to some degree not actually but close enough to illustrate the point) (Read more:

class ParentComp extends React.Component {
  constructor() {
    this.state = {
      fruits: ['Apple', 'Orange', 'Banana', 'Pomegranate', 'Kiwi']

  addFruit = () => {
    let newFruits = Object.assign([], this.state.fruits);

  setFruits = (fruits) => {

  saveFruits = () => {

  render() {
    return ( 
         {, key) => {
          return (<div key={key}>{fruit}</div>) })} 
          <button type="button" onClick={this.addFruit}>Add Peach</button>
ReactDOM.render(<ParentComp /> , document.getElementById('root'))
<script src=""></script>
<script src=""></script>

<div id="root"></div>

We get the same problem above but it might be a little clearer. The setState for fruits does get called but the console.log happens before the state/render change happens so this.state.fruits is still referring to what was in the state before.

I highly recommend reading React hooks: not magic, just arrays to get a better sense of what goes on behind the scenes of hooks. It helps explain it a lot.


You can try with useEffect which will give updated state whenever there will be update.

useEffect(() => {
  }, [fruits]);

Related Query

More Query from same tag