Answers for "usestate hook callback"

32

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>
    </>
  );
}
Posted by: Guest on March-29-2020
7

usestate hook

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Posted by: Guest on September-08-2020
0

useState hook with callback

const [state, setState] = useState(null);
const myCallbacksList = useRef([]);
const setStateWithCallback= (newState, callback) => {
  setState(state);
  if(callback) myCallbackList.current.push(callback)
}
useEffect(() => {
  myCallbacksList.current.forEach((callback) => callback())
  myCallbacksList.current = [];
}, [state]);
…
setStateWithCallback(newState, myCallback)
Posted by: Guest on October-19-2021
0

usestate hook callback

const [counter, setCounter] = useState(0);

const doSomething = () => {
  setCounter(123);
}

useEffect(() => {
   console.log('Do something after counter has changed', counter);
}, [counter]);
Posted by: Guest on April-17-2021

Browse Popular Code Answers by Language