Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect does not detect prop change of setState from parent component

I have an array of participant components that i construct from participants list like this:

function parent({addr}){
const [winner, setWinner] = useState(null);
const [participants,setParticipants] = useState([{id:0,name:"user0"}]);
useEffect(()=>
   {
     participants.map((elem,index)=> <Participant key={index} participant={elem} winner={winner}/>); 
     countWinner();
   },[addr])

 function countwinner()
 {
    setWinner(prev => {return {id:0,count:5}})
 }
}

inside the child component; i monitor the change of winner by using useEffect():

function Participant({winner})
{
  useEffect(()=>
  {
    console.log("winner variable changed",winner)
  },[winner]);
}

the output of logging winner is always null.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS: I added useEffect inside parent and it is updating correctly, it just does not update in the child list.

>Solution :

what you done wrong is:

  1. just change this line setWinner(prev => {return {id:0,count:5}}) to setWinner(prev => ({id:0,count:5}.
  2. what the hell you are using map in useEffect.

take a look to this snippet of parent.

import React, { useState, useEffect } from 'react';                
import Participant from './Participant';

function Parent({ addr }) {
   const [winner, setWinner] = useState(null);
   const [participants, setParticipants] = useState([{ id: 0, name: 'user0' }]);

   useEffect(() => {
     countWinner();
   }, [addr]);

  function countWinner() {
     setWinner((prev) => ({ id: 0, count: 5 }));
  }

  return participants.map((elem, index) => (
     <Participant key={index} participant={elem} winner {...winner} />
  ));
}
export default Parent;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading