A component has 2 child components, on changing the switch value in one of the child component, it should re-render the other child component. How to achieve this? Please explain with a code snippet.
React components render/rerender for one of a couple reasons:
Causing case 2 is the simplest way to achieve what you ask. The parent component of both children just needs some declared state that child 1 can call a callback prop when it updates its local state to trigger the parent component to rerender itself and its sub-ReactTree.
Example:
const Child1 = ({ onChange }) => {
const [value, setValue] = React.useState();
React.useEffect(() => {
onChange(value);
}, [onChange, value]);
return (
<React.Fragment>
<h1>Child 1</h1>
<label>
Value
<input
type="checkbox"
value={value}
onChange={(e) => setValue(e.target.checked)}
/>
</label>
</React.Fragment>
);
};
const Child2 = () => {
React.useEffect(() => {
console.log("Child 2 render " + new Date());
});
return <h1>Child 2</h1>;
};
function App() {
const [, rerender] = React.useState();
return (
<div className="App">
<Child1 onChange={rerender} />
<Child2 />
</div>
);
}
const rootElement = document.getElementById("root");
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root" />
There are other ways to trigger sibling components to rerender via a common ancestor component, like a React Context provider.