The White Rabbit

It is better to be approximately right than precisely wrong. (Warren Buffet)

Published on Thursday, 9 March 2023

Tags: reactjs2 code5

Store/Update state object after asynchronous changing its value in ReactJS

State variables can be changed as soon as they change values. Here's how to do it using useCallback() function.

Let's assume you've defined a state called "variable" in some component through useState and initialized it to null.

const [ variable, setVariable] = useState(null);

Now you need to call an (async) function to load data from memory (or any backend endpoint) - let's say loadData - and put its result back in "variable".

const fetchData = useCallback(async()=> { const data = await loadData(); setVariable(variable)}, []);
useEffect(() => {fetchData()}, []);


The useCallback() hook is used to let React "cache" (=memoize) a function instead of re-creating it at every re-rendering. Passing an empty array as dependencies to useCallback (as I did in the above example) will achieve this purpose. Therefore, the implemented function's body is created only once at the first rendering. Of course, if you want exceptionally to re-create the fetchData function for some states change, just provide them in the dependencies array.

Afterwards, the useEffect hook will execute the previously defined callback fetchData only once (because of the empty dependencies array).