I have two components in my project.
One is Aapp.jsx
One is Child.jsx
When I called the state set function in Child 1; it is supposed to see mentioning child 1 in the console, but now it is showing child 3. It is weird and why is that?
I guess the reason is "key" in prop, so I added "key" there too. But the problem is still there.
Here is the code: App:
import React,{useState,useEffect} from 'react';
import {Child} from './Child.jsx'
export function App(props) {
[message,setMessage]=useState('');
[showChild1,setShowChild1]=useState(true);
[showChild2,setShowChild2]=useState(true);
[showChild3,setShowChild3]=useState(true);
[child1data,setChild1data] = useState('child1');
[child2data,setChild2data] = useState('child2');
[child3data,setChild3data] = useState('child3');
useEffect(() => {
console.log('parent was rendered')
})
return (
<div className='App'>
<button onClick={()=>setShowChild1(!showChild1)}>Show child1</button>
{showChild1 && <Child key='1' data={child1data}/>}
<br/>
<br/>
<button onClick={()=>setShowChild2(!showChild2)}>Show child2</button>
{showChild2 && <Child key='2'data={child2data}/>}
<br/>
<br/>
<button onClick={()=>setShowChild3(!showChild3)}>Show child3</button>
<br/>
{showChild3 && <Child key='3' data={child3data}/>}
</div>
);
}
// Log to console
console.log('Hello console')
Child:
import React, {useState, useEffect} from 'react';
export const Child = (props) => {
const {data} = props;
[message,setMessage]=useState('');
useEffect(()=>{
console.log(data)
console.log(message)
})
return <>
<h1>This is {data}</h1>
<input onChange={((e)=>setMessage(e.target.value))}></input>
</>
}
For better illustrate, here is my code https://playcode.io/940717
