use callback react 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: use callback vs use memo
useCallback(() => {···}, [dependency1, dependency2]);
useMemo(() => {···}, [dependency1, dependency2]);
Example 3: callback in react
import React, { useCallback } from 'react';
function MyComponent() {
const handleClick = useCallback(() => { console.log('Clicked!'); }, []);
}
Example 4: react callback
import React, {useState} from 'react';
function newCallback(callback) {
callback('This can be any value you want to return')
}
const Callback = () => {
const [callbackData, setCallbackData] = useState('')
function actionAferCallback (callback) {
setCallbackData(callback)
}
function requestCallback() {
newCallback(actionAferCallback)
}
return(
<div>
{}
<button onClick={() => {requestCallback()}}>Request Callback</button>
{callbackData}
</div>
)
}
export default Callback;