“Rappel UseState” Réponses codées

Rappel UseState

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

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

useEffect(() => {
   console.log('Do something after counter has changed', counter);
}, [counter]);
Troubled Termite

Comment utiliser le rappel `SetState` sur React Hooks

//You need to use useEffect hook to achieve this.

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

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

useEffect(() => {
   console.log('Do something after counter has changed', counter);
}, [counter]);
Marty McFly

UseState Hook avec rappel

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)
Splendid Salmon

Réponses similaires à “Rappel UseState”

Questions similaires à “Rappel UseState”

Plus de réponses similaires à “Rappel UseState” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code