const Parent = ({ initialData }) => {
const [data, setData] = React.useState(initialData);
console.log('render Parent');
return <>
<h2>Parent</h2>
<input
placeholder="title"
value={data.title}
onChange={
React.useCallback((e) => {
setData(prev => ({ ...prev, title: e.target.value }))
}, [])
}
/>
<br />
<Child1
data={data}
onChange={
React.useCallback((prop, value) => {
setData(
prev => {
prev[prop] = value;
const newState = { ...prev };
return newState;
}
);
}
, []
)
}
/>
</>
}
const Child1 = React.memo(
({ data, onChange }) => {
console.log('render Child1');
return <>
<h3>Child1</h3>
<input
placeholder="description"
value={data.description}
onChange={(e) => { onChange('description', e.target.value) }}
/>
<br />
<br />
<br />
{data.list.map((element, index) => {
return <Child2
key={index} // don't do this in real
index={index}
data={element}
onChange={
React.useCallback(
(prop, value) => {
const newList = data.list.map((e, i) => {
let newItem = { ...e };
if (i == index) {
newItem[prop] = value;
}
return newItem;
});
onChange('list', newList);
}
,
[]
)
}
/>
})}
</>
}
)
const Child2 = React.memo(({ index, data, onChange }) => {
console.log('render Child2', index);
return (
<>
<h4>Child2</h4>
Country: <br />
<input
placeholder="country"
value={data.country}
onChange={(e) => onChange('country', e.target.value)}
/>
<br />
<br />
Region: <br />
<input
placeholder="region"
value={data.region}
onChange={(e) => onChange('region', e.target.value)}
/>
<br />
<br />
City: <br />
<input
placeholder="city"
value={data.city}
onChange={(e) => onChange('city', e.target.value)}
/>
<hr />
</>
)
}
)
React.useCallback((key, val) => {
setData(data => ({
...data,
[key]: val(data[key]),
}));
}, [])
onChange('list', list => list.map((n, i) => i === index
? { ...n, [prop]: value }
: n
))
onChange('description', () => e.target.value)