You can pass data between React components in several ways, depending on the relationship between components:
✅ 1. Parent to Child (via Props)
➡️ The most common method.
function Parent() {
return <Child name="Teekam" />;
}
function Child({ name }) {
return <p>Hello, {name}</p>;
}
✅ 2. Child to Parent (via Callback Functions)
➡️ Pass a function from parent and call it in the child.
function Parent() {
const handleData = (data) => {
console.log("Received:", data);
};
return <Child sendData={handleData} />;
}
function Child({ sendData }) {
return <button onClick={() => sendData("Hi Parent")}>Send</button>;
}
✅ 3. Sibling to Sibling (via Parent)
➡️ Share data using a common parent.
function Parent() {
const [data, setData] = useState("");
return (
<>
<SiblingA setData={setData} />
<SiblingB data={data} />
</>
);
}
✅ 4. Using Context API
➡️ For deeply nested or global data (like theme, auth).
const UserContext = React.createContext();
function App() {
return (
<UserContext.Provider value="Teekam">
<Profile />
</UserContext.Provider>
);
}
function Profile() {
const user = useContext(UserContext);
return <p>Welcome, {user}</p>;
}
✅ 5. Global State Libraries
➡️ Use tools like Redux, Zustand, or Jotai for large apps.