use callback react code example

Example 1: useRef

/*
	A common use case is to access a child imperatively: 
*/

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

Example 2: use callback vs use memo

// They both take a function and an array of dependencies:

useCallback(() => {···}, [dependency1, dependency2]);
useMemo(() => {···}, [dependency1, dependency2]);

// So what is the difference? 

// useCallback returns its function uncalled so you can call it later
// therefore, it gives you back the function's reference

// useMemo calls its function and returns the result.
// therefore, it gives you back the function's return value

Example 3: callback in react

import React, { useCallback } from 'react';

function MyComponent() {
  // handleClick is the same function object
  const handleClick = useCallback(() => {    console.log('Clicked!');  }, []);
  // ...
}

Example 4: react callback

import React, {useState} from 'react';

// Create a callback in the probs, in this case we call it 'callback'
function newCallback(callback) {
  callback('This can be any value you want to return')
}

const Callback = () => {

const [callbackData, setCallbackData] = useState('')

// Do something with callback (in this case, we display it on screen)
function actionAferCallback (callback) {
  setCallbackData(callback)
}

// Function that asks for a callback from the newCallback function, then parses the value to actionAferCallback
function requestCallback() {
  newCallback(actionAferCallback)
}

  return(
    <div>
      {/* A button to activate callback */}
      <button onClick={() => {requestCallback()}}>Request Callback</button>
      {callbackData}
    </div>
  )
}

export default Callback;