Expose Counter Methods Via Refs In React
Expose component methods via refs with `useImperativeHandle`. Create an interface to share state between components without lifting state up or using context.
Let's build a case Imagine you have a counter—a classic, simple counter component. function Counter(){ const [counter, setCounter] = useState(0) const handleIncrement = ()=> setCounter(counter + 1) return ( <> <p>Counter: {counter}</p> <button onClick={handleIncrement}>Inc</button> </> ) } function App(){ return ( <> <Counter /> </> ) } Now, for some reason, you're asked to add a second button that increments the counter but is placed somewhere far away from the Counter component—although still on the same screen. Th...