How to pass data between React Components

Venkatesh Kamalapathy
Towards Dev
Published in
2 min readJan 4, 2022

--

Data handling in React is not as complicated as it might seem. Hope you have gone through react docs where they have class components without typescript.

Photo by Lautaro Andreani on Unsplash

My examples here will be using typescript with functional react components.

Choose the common ancestor to handle the data between its children

It’s been recommended to lift the shared state up to their closest common ancestor.

Let’s assume we have a parent and 2 child components. One child provides data and another child consumes it.

Code:

Let’s start with the Consumer which requires data.

export type ConsumerChildPropType = {name: string};export function ConsumerChild(props: ConsumerChildPropType) {
return (
<>
<h1>{props.name}</h1>
</>
);
}

Next, We define another child which provides data.

export function ProducerChild(prop: {onStateChange: (name: string ) => void}) {
let [name, setName] = useState('');

useEffect(() => {
prop.onStateChange(name);
}, [name]);

return (<>
<input type='text' onChange={(t) => setName(t.target.value) }/>
</>);
}

Finally, we have Parent which holds ProducerChild and ConsumerChild and transfers data from one component to another.

export function Parent() {
let [name, setName] = useState('');

function nameChange(newName: string) {
setName(newName);
}

return (
<>
<ConsumerChild name={name}/>
<ProducerChild onStateChange={nameChange}/>
</>
);
}

Output:

ProducerChild receives input and instantly updates ConsumerChild

--

--

A Polyglot Developer and a Competitive Programmer. Interested in web technologies, cloud computing and electronics.