React solution where state is managed in the Child (Counter) and the Parent (App) controls increment via a button.
✅ Key Requirement Breakdown
- Counter value is stored in Child
- Button is in Parent
- Parent triggers increment without owning state
- Achieved using
ref + useImperativeHandle
🔹 Child Component (Counter.jsx)
import React, { useState, forwardRef, useImperativeHandle } from "react";
const Counter = forwardRef((props, ref) => {
const [count, setCount] = useState(0);
useImperativeHandle(ref, () => ({
increment() {
setCount(prev => prev + 1);
}
}));
return <h2>Count: {count}</h2>;
});
export default Counter;
🔹 Parent Component (App.jsx)
import React, { useRef } from "react";
import Counter from "./Counter";
function App() {
const counterRef = useRef();
return (
<div>
<Counter ref={counterRef} />
<button onClick={() => counterRef.current.increment()}>
Increment
</button>
</div>
);
}
export default App;
🧠 How This Works
- Child owns the state (
count) - Child exposes methods via
useImperativeHandle - Parent calls child’s method using
ref - No state lifting, clean separation
🎯 Short Interview Answer
The child manages the counter state, and the parent interacts with it using
useRefanduseImperativeHandle. This allows the parent to trigger updates without owning the state.
⭐ One-line summary
State stays in the child; parent controls behavior using refs.