With flushSync() inside useEffect do we do the same as using useLayoutEffect? - javascript

https://reactjs.org/docs/react-dom.html#flushsync
Force React to flush any updates inside the provided callback
synchronously. This ensures that the DOM is updated immediately.
// Force this state update to be synchronous.
flushSync(() => {
setCount(count + 1);
});
// By this point, DOM is updated.
Knowing that, it is the same as using useLayoutEffect, or do I misunderstand flushSync()?
const App = () => {
const [name, setName] = React.useState("Leonardo");
React.useEffect(() => {
ReactDOM.flushSync(() => {
for (let index = 1; index <= 100000; index++) { // for simulate blocking
console.log(index);
}
setName("Jose");
});
});
return (
<div>
<h1>Hello {name}</h1>
</div>
);
};
¿it is the same that this?
React.useLayoutEffect(() => {
for (let index = 1; index <= 100000; index++) {
console.log(index);
}
setName("Jose");
});

useLayoutEffect is useful for things that need to happen before paint your dom or when your code is causing flickering. it's already synchronous and executed always before every useEffect hook in your code.
flushSync is used to convert the setState into synchronous. in 99% of cases you will use flushSync inside a handler like a form submit handler, outside of useEffect to execute an imperative action
function handleSubmit(values) {
flushSync(() => {
setForm(values);
});
}
Be aware that flushSync force a re-rendering, so use it carefully
The common use case of flushSync is update the DOM after settings the state immediately. example scroll to the new added element in the list
flushSync(() => {
setElements((elements) => [
...elements,
{
id: 'random',
},
]);
});
// scroll to element here
Check this example https://codesandbox.io/s/react-18-batching-updates-flushsync-forked-vlrbq8. you can delete flushSync and see the diff

flushSync is used to force React to flush a state update and when you try to put it inside useEffect it won't affect when useEffect is invoked, it will always be after the changes have been reflected on the browser, whereas useLayoutEffect is invoked before and this is the main difference between them.
so flushSync is not a function that is supposed to be executed inside useEffect you will even get this warning
Warning: flushSync was called from inside a lifecycle method. React cannot flush when React is already rendered. Consider moving this call to a scheduler task or microtask.

They are not same. Your code might give the same performance, functional, and results, yet they are different in nature.
flushSync is a low-level API that flushes updates to the React DOM immediately, bypassing the normal scheduling mechanism. It should be used sparingly and only when necessary, as it can lead to poor performance and is more prone to bugs and inconsistencies. On the other hand, useLayoutEffect is a higher-level hook that schedules a DOM update to happen synchronously after all other updates have been processed. It is generally the preferred way to ensure that updates are synchronized with the layout of the page.

I did this code to see if I understood everything, please correct me:
function App2() {
const [c, setC] = React.useState(0);
const inc1 = () => {
/*setC is asynchronous (withoutFlushSync), so it continues the
code downwards and therefore from the DOM it
brings us the value without increment in 1*/
setC((c) => c + 1);
console.log(document.getElementById("myId").innerText); // old value from DOM
console.log(c); // However below log will still point to old value ***BECAUSE OF CLOSURE***
};
const inc2 = () => {
/*waits until the DOM is modified with the new state (in the first click
c = 1)*/
ReactDOM.flushSync(() => { // Wait
setC((c) => c + 1);
});
/* brings the c = 1 of the DOM because it waited until the DOM
was modified with the new state incremented by one. */
console.log(document.getElementById("myId").innerText); // new value from DOM
console.log(c); // However below log will still point to old value ***BECAUSE OF CLOSURE***
};
return (
<div className="App">
Count: <div id="myId">{c}</div>
<button onClick={inc1}>without flushSync</button>
<button onClick={inc2}>with flushSync</button>
</div>
);
}

Related

Related to weird behaviour of react useState and useEffect

import {useEffect,useState} from 'react';
export default function App() {
const [count,setCount]=useState(0);
const [flag,setFlag]=useState(false);
function increment(){
setCount(prevState=>{
if(flag)
return prevState
return prevState+1;
});
}
useEffect(function(){
increment();
setFlag(true);
increment();
},[]);
return (
<div className="App">
{count}
</div>
);
}
Was playing around with effects and states in reatct functional component, I expected the code to output "1" but it's giving the output as "2", Why is it happening and How can I make it print 1 ?
Once you call setFlag, React will update the returned value of your useState call [flag,_] = useState() on the next render.
Your setFlag(true) call schedules a re-render, it doesn't immediately update values in your function.
Your flag is a boolean const after all -- it can't be any value but one value in that function call.
How to solve it gets interesting; you could put the the flag inside of a single state object i.e. useState({count: 0, flag: false})
But more likely, this is an academic problem. A count increment sounds like something that would trigger on a user interaction like a click, and so long as one function doesn't call increment() multiple times (this sounds unusual), the re-render will happen in time to update your flag state.
For performance reasons, React defers useState hook updates until function completes its execution, i.e. run all statements in the function body and then update the component state, so React delays the update process until a later time.
Thus, when increment function execution is completed, React updates the state of count. But for setFlag method, the execution environment is a context of useEffect hook's callback, so here React's still waiting for a completion of useEffect's callback function. Therefore, inside the callback of useEffect the value of flag is still false.
Then you again called your increment function and when this function finished its execution, your count again was incremented by 1.
So, in your case, the key factor is the way of deferring state updates until function execution by React.
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.
React Component: setState()
For more information, you can also read about Batch updates in React (especially in React 18) or Reactive programming (this is not React), where the main idea is real-time or timely updates.
For a better understanding I would think it of as replacing the invocation directly with setter and we know how the state batching works so ...
import { useEffect, useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
useEffect(function () {
// increment(); becomes below
setCount((prevState) => {
if (flag) return prevState;
return prevState + 1;
});
// queued update count returns
// count => count + 1 0 0 + 1 = 1
setFlag(true);
//set flag=true in next render
// increment(); becomes below
setCount((prevState) => {
if (flag) return prevState;
return prevState + 1;
});
// so flag is still false here and count is 1
// queued update count returns
// count => count + 1 1 1 + 1 = 2
// done and count for next render is 2 and flag will be false
}, []);
return <div className="App">{count}</div>;
A better explaination in Docs - Queueing state updates and state as snapshot
State updates are "batched". See the other answers for an explanation. Here's a workaround using useRef - since a ref can be updated during this render, you can use it like a "normal" variable.
const { useState, useRef, useEffect } = React;
function App() {
const [count, setCount] = useState(0);
const flag = useRef(false);
function increment() {
setCount(prevState => {
if (flag.current)
return prevState;
return prevState + 1;
});
}
useEffect(function() {
increment();
flag.current = true;
increment();
}, []);
return <div className="App">{count}</div>;
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Can't reach value in async function with setInterval - JavaScript

I'm trying to do automated card pull started with button, and stop it when croupierCount reach 17, using setInterval. Value of croupierCount changes (<div> displays this count) with this function below, but when I'm trying to reach this value inside function to stop interval, it's logged value is 0. Can you help me solve this?
const TheGame = () => {
const [croupierCount, setCroupierCount] = useState(0);
const [croupierHand, setCroupierHand] = useState([]);
const onStandHandler = () => { // triggered with button
const croupierInterval = async () => {
let card = await fetchCard(deck); // fetching new card with every iteration (works)
croupierHand.push(card); // pushes fetched card (works)
if (card[0].value === 'ACE') {
setCroupierCount((prevCount) => prevCount + 11);
}
else if (card[0].value === 'JACK' || card[0].value === 'QUEEN' || card[0].value === 'KING') {
setCroupierCount((prevCount) => prevCount + 10);
}
else {
setCroupierCount((prevCount) => prevCount + Number(card[0].value));
};
// croupierCount is changing (I'm displaying it in div)
console.log(croupierCount); // croupierCount = 0, I don't know why.
if(croupierCount > 17) {
clearInterval(startInterval);
};
}
const startInterval = setInterval(croupierInterval, 1000);
};
};
You seem to miss an important point: using const here...
const [croupierCount, setCroupierCount] = useState(0);
... makes croupierCount a constant value, regardless of how many times setCroupierCount is called. This variable cannot be updated directly: what you see as its update is actually changes in React internal state, represented by the same name when the component is rerendered - and render function is called again.
This immutability is both a blessing and a curse typical to hook-based functional components.
Here's what happens here:
when component is rendered, TheGame function is called first time. Its useState call initializes both value and the corresponding setter as a part of internal React state tied to this component's instance.
Those values are returned from useState function - and are stored in local variables (constants!) of TheGame function, croupierCount and setCroupierCount. What's important - and often missed - is that these particular variables are created anew each time TheGame function is called!
then onStandHandler function is created, having both aforementioned local variables available as part of its scope.
at some point, onStandHandler function is triggered (when user presses a button). It creates yet another function, croupierInterval, which should fetch data first, then update the state by calling setCroupierCount with result of this fetch.
There are two problems with this function, though.
First, all croupierInterval sees is values of current croupierCount and setCroupierCount variables. It cannot magically 'peek' into which values those variables will carry when rerender is triggered and TheGame function is executed next time - as those will be new variables actually!
But there's a bigger problem you seem to miss: setInterval doesn't play nicely with fetch (or any async action). Instead of waiting for the processing of that action, you just make JS trigger this function periodically.
Not only this messes up with an expected delay (slow down fetch so that it takes 10 seconds, then see what happens), but there's an actual bug here: as clearInterval(startInterval) doesn't stop processing all the parts of a function that follow await fetchCard(deck), in the worst case, your Croupier might go way above 17.
This is for 'why' part, but what's on 'how to fix'? There are several things worth trying here:
avoid using setInterval in functional components like a plague: there are often far better replacements. In this case in particular, you should've at least tied setting up calling croupierInterval to the previous call's completion
useEffect whenever you want something to modify your state indirectly as some kind of side-effect. Not only this makes your code easier to read and understand, but also lets you clear out the side effects of side effects (like timeouts/intervals set)
don't forget to handle human errors, too: what should happen if a user mistakenly double-clicks this button?
I'm posting my solution, if someone encounters a similar problem.
const isMount = useRef(false);
...
useEffect(() => {
if (isMount.current && croupierCount !== 0) {
if (croupierCount < 17) {
setTimeout(() => {
onStandHandler();
}, 1000);
}
}
else isMount.current = true;
}, [croupierCount]);
const onStandHandler = async () => {
let card = await fetchCard(deck, 1);
croupierHand.push(card);
if (card[0].value === 'ACE') {
setCroupierCount(prevCount => prevCount + 11);
}
else if (card[0].value === 'JACK' || card[0].value === 'QUEEN' || card[0].value === 'KING') {
setCroupierCount(prevCount => prevCount + 10);
}
else {
setCroupierCount(prevCount => prevCount + Number(card[0].value));
};
};

Too many re-renders even though I want an infinite loop

I'm trying to create a simple idle game so that I can dive deeper into web development.
However, react is complaining about too many re-render, but I do want to re-render every second.
This is the code I have at the moment.
> const Game = () => { const [resourceCopper, setResourceCopper] =
> useState(0);
>
> const gatherCopper = () => {
> setResourceCopper(resourceCopper + 1); };
>
> setInterval(gatherCopper(), 1000);
>
> return (
> <section className="main-window-container">
> <section className="left-container">
> <h3>Resources:</h3>
> <p>Copper: {resourceCopper}</p>
> </section>
The immediate issue is that you're immediately executing gatherCopper, which immediately updates the state, rerender, and will cause an infinite loop.
You should remove the () behind gatherCopper in the setInterval call.
However, this code is very leaky, and because of the way React works you will create a new interval for every time the component renders. This will not work as expected.
The interval should be moved to a a React hook (i.e. useEffect), perhaps there's even hooks which wrap setInterval. A google search will probably come up with some good examples.
With React hooks you'll be able to start the interval when the component mounts for the first time, and you can also tell it to cancel the setInterval when the component unmounts. This is important to do.
update: Example with annotations (sandbox link)
const Game = () => {
const [resourceCopper, setResourceCopper] = useState(0);
useEffect(() => {
// We move this function in here, because we only need this function once
const gatherCopper = () => {
// We use the 2nd way of calling setState, which is a function that will
// receive the current value. This is so that we don't have to use the resourceCopper
// as a dependency for this effect (which would fire it more than once)
setResourceCopper(current => current + 1);
};
// We tell the setInterval to call the new gatherCopper function
const interval = setInterval(gatherCopper, 1000);
// When an effect returns a function, it will be used when the component
// is cleaned up (a.k.a. dismounts). We want to be neat and cancel up the interval
// so we don't keep calling this on components that are no longer there
return () => clearInterval(interval);
}, [setResourceCopper]);
return (
<section className="main-window-container">
<section className="left-container">
<h3>Resources:</h3>
<p>Copper: {resourceCopper}</p>
</section>
</section>
);
};

Having some troubles getting useEffect, useCallback and setTimeout to work together

Trying to implement some custom scroll behaviour for a slider based on the width. It's using useState, to keep track of the current and total pages inside the slider. This is the code I have ended up with trying to acomplise it but it has some unexpected behaviour.
const [isTimeoutLocked, setIsTimeoutLocked] = useState(false)
const handleScroll = useCallback(() => {
const gridContainer = document.querySelector(".grid");
const totalPages = Math.ceil(
gridContainer.scrollWidth / gridContainer.clientWidth + -0.1
);
setTotalPages(totalPages);
const scrollPos = gridContainer.clientWidth + gridContainer.scrollLeft + 2;
if (gridContainer.scrollWidth > scrollPos) {
gridContainer.scrollBy({
left: gridContainer.clientWidth + 20.5,
behavior: "auto",
block: "center",
inline: "center",
});
setCurrentPage(currentPage + 1);
setIsTimeoutLocked(false)
} else {
gridContainer.scrollTo(0, 0);
setCurrentPage(1);
setIsTimeoutLocked(false)
}
},[currentPage]);
useEffect(() => {
if(!isTimeoutLocked){
setTimeout(() => {
setIsTimeoutLocked(true)
document.querySelector(".grid") && handleScroll();
}, 5000);
}
}, [currentPage, displayDate, isTimeoutLocked, handleScroll]);
The problem here is that when the currentPage is displayed in the ui it will reset back to one if the else runs inside the handleScroll function which is totally fine but then it will result back to the previous value instead of going back to 2 when it gets to the next page. Also since I have added the isTimeoutLocked as a dependency to the useEffect since it was asking for it the setTimeout will run more often but I only want to have it as a dependency to get the correct value not so the useEffect runs everytime it changes. The purpose of the isTimeoutLocked is so when you change the content inside the container by changing the current day it has not registered a bunch of timeouts.
You should add a cleanup function to your useEffect. Since you mutate isTimeoutLocked in your useEffect it can force multiple setTimeouts to run and that is probably the result of wierd behaviour.
When using setTimeout inside useEffect it is always recommended to use it with cleanup. Cleanup will run before the next useEffect is triggered, that gives you a chance to bail out of next setTimeout triggering. Code for it is this:
useEffect(() => {
if(!isTimeoutLocked){
const tid = setTimeout(() => {
setIsTimeoutLocked(true)
document.querySelector(".grid") && handleScroll();
}, 5000);
// this is the cleanup function that is run before next useEffect
return () => clearTimeout(tid);
}
You can find more information here: https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup .
Another thing to be careful is the async nature of setState and batching. Since you are using setState inside a setTimeout, React will NOT BATCH them, so EVERY setState inside your handleScroll will cause a rerender (if it was not inside a setTimeout/async function React would batch them). Since you have alot of interconected states you should look into useReducer.

React Hooks useEffect to call a prop callback from useCallback

I'm trying to make a general-purpose infinite scroller with React Hooks (and the ResearchGate React Intersection Observer). The idea is that a parent will pass down a mapped JSX array of data and a callback that will asynchronously get more data for that array, and when the intersection observer fires because you've scrolled down enough to reveal the loading icon, the callback gets called and more data is loaded.
It works well enough, except one thing: esLint tells me that because I'm calling the getMore function (from the props) inside a useEffect, it must be a dependency of that effect. But because in the parent's callback I'm accessing its data array's length, that array must be a dependency of useCallback there. And then that callback modifies the array.
TL;DR: I'm getting race conditions that cause the async callback to trigger multiple times when it shouldn't, because the callback function reference is changing and then being passed down to the thing that's calling it.
Here's some code to clarify.
The callback in the parent:
const loadData = useCallback(async () => {
if (hasMore) {
const startAmount = posts.length;
for (let i = 0; i < 20; ++i) {
posts.push(`I am post number ${i + startAmount}.`);
await delay(100);
}
setPosts([...posts]);
setHasMore(posts.length < 100);
}
}, [posts, hasMore]);
posts and hasMore are just state variables, with posts being passed down as the data array in props to the child. That function is being passed to the child in props, which has this (getMore is the destructured prop for the callback, isLoading is just a boolean state variable):
useEffect(() => {
if (isLoading) {
(async () => {
await getMore();
setIsLoading(false);
})();
}
}, [isLoading, getMore]);
I'm setting isLoading to true to trigger the effect; but it's also triggering because getMore's reference changes when the parent loads data and the function memoizes. That shouldn't happen. I could just disable esLint for that line, but I assume there's a better solution, and I'd like to know what it is.
Solution: don't use useEffect at all. Just call the loading function directly from the observer and have that set isLoading and call the callback rather than having isLoading trigger the callback.
const loadData = async (observerEntry) => {
if (observerEntry.isIntersecting && !disabled && !isLoading) {
setIsLoading(true);
await getMore();
setIsLoading(false);
}
};

Categories