react useimperativehandle code example
Example 1: useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Example 2: react reducer hooks
import React from "react";
const initialState = {counter: 0};
const INC = 'INCREMENT';
const DEC = 'DECREMENT';
function incActionCreator() {
return {
type: INC,
}
}
function decActionCreator() {
return {
type: DEC,
}
}
function hooksReducer(state, action) {
switch(action.type) {
case 'INCREMENT':
return {
...state,
counter: state.counter++
}
case 'DECREMENT':
return {
...state,
counter: state.counter--
}
default:
return state;
}
}
function App () {
const [stateAction, setDispatchAction] = React.useReducer(hooksReducer, initialState);
const incClick = (e) => setDispatchAction(incActionCreator())
const decClick = (e) => setDispatchAction(decActionCreator())
return (
<>
<button onClick={incClick}>Incerement</button>
<button onClick={decClick}>Decrement</button>
<h4>Counter: {stateAction.counter}</h4>
</>
);
}
export default App;