React
Component Communication
Parent-child and sibling component communication.
By EZ4Code Team
reactcommunication
Code
import { useState, createContext, useContext } from 'react';
// Parent to child: props
function Parent() {
const [message, setMessage] = useState('Hello');
return <Child message={message} onReply={(msg) => console.log(msg)} />;
}
function Child({ message, onReply }) {
return (
<div>
<p>{message}</p>
<button onClick={() => onReply('Hi')}>Reply</button>
</div>
);
}
// Child to parent: callback
function TodoList() {
const [todos, setTodos] = useState([]);
const addTodo = (text) => {
setTodos([...todos, { id: Date.now(), text }]);
};
return <TodoForm onAdd={addTodo} />;
}
function TodoForm({ onAdd }) {
const [text, setText] = useState('');
return (
<form onSubmit={e => { e.preventDefault(); onAdd(text); setText(''); }}>
<input value={text} onChange={e => setText(e.target.value)} />
</form>
);
}
// Sibling communication: state lifting
function App() {
const [selected, setSelected] = useState(null);
return (
<>
<List items={items} onSelect={setSelected} />
<Detail item={selected} />
</>
);
}
// Cross-level: Context
const SelectedContext = createContext();
function GrandChild() {
const selected = useContext(SelectedContext);
return <div>{selected?.name}</div>;
}
// Event bus (simple implementation)
const bus = {
listeners: {},
on(event, cb) {
(this.listeners[event] = this.listeners[event] || []).push(cb);
},
emit(event, data) {
(this.listeners[event] || []).forEach(cb => cb(data));
}
};Explanation
React component communication: props passing, callback functions, state lifting, Context across levels, event bus.
More React Snippets
Controlled Form with Validation
Build a controlled React form with inline validation and error messages.
Event Handling and List Rendering
Handle events and render dynamic lists with keys in React.
useState
State management Hook.
useEffect
Side-effect Hook.
useContext
Shared state via context.
useReducer
Complex state management.