React Hooks: State always setting back to initial value - javascript

Switching over to react hooks and using them for the first time. My state always seems to be set back to the initial value I pass it (0). Code is to have a page automatically scroll down and up. The page is just practice to displaying various file types. What happens is the scrollDir variable will switch to being set to either 1 or -1 and 0. So the console will display 1,0,1,0,1,0,1,0 etc... How do I get the state to stay during an update?
function App(props) {
const [scrollDir, setScrollDir] = useState(0);
function scrollDown() {
if(document.documentElement.scrollTop < 10)
{
setScrollDir(1);
}
else if(document.documentElement.scrollTop >= document.documentElement.scrollHeight - window.innerHeight)
{
setScrollDir(-1);
}
window.scrollBy(0, scrollDir);
}
useEffect(() => {
setInterval(scrollDown, 100);
});
return (
<StackGrid monitorImagesLoaded={true} columnWidth={"33.33%"} >
<img src={posterPNG} />
<img src={posterJPG} />
<img src={posterGIF} />
<video src={posterMP4} loop autoPlay muted />
<Document file={posterPDF}>
<Page pageNumber={1} />
</Document>
</StackGrid>
);
}

useEffect hook takes second argument, an array.
If some value in that array changes then useEffect hook will run again
If you leave that array empty useEfect will run only when component mount - (basicaly like ComponentDidMount lifecycle method)
And if you omit that array useEffect will run every time component rerenders
For example:
useEffect runs only once, when component mounts:
useEffect(() => {
//code
},[]);
useEffect runs everytime when component rerenders:
useEffect(() => {
//code
});
useEffect runs only when some of these variables changes:
let a = 1;
let b = 2;
useEffect(() => {
//code
},[a,b]);
Also, if you set return statement in useEffect hook, it has to return a function, and that function will always run before useEffect render
useEffect(() => {
// code
return () => {
console.log("You will se this before useEffect hook render");
};
}, []);

Using setInterval with hooks isn't very intuitive. See here for an example: https://stackoverflow.com/a/53990887/3984987. For a more in-depth explanation you can read this https://overreacted.io/making-setinterval-declarative-with-react-hooks.
This useInterval custom hook is pretty easy to use as well https://github.com/donavon/use-interval. (It's not mine - I ran across this after responding earlier)

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>

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>
);
};

Timer goes crazy when using setInterval inside useEffect

So I've been trying to learn the fundamentals of React and tried something like this which made the code go crazy. It looks like all the digits change wildly fast starting from the initial one and after a while the browser gives warnings like
"setInterval" is taking 205ms
Tried adding timer as a dependency and even returning it. It's all a little confusing to me. Can someone please explain to me in depth what's happening here?
import {useState, useEffect} from 'react'
function App() {
const [timer, setTimer] = useState(0)
useEffect(()=>{
setInterval(()=>{
setTimer(timer + 1)
}, 1000)
},[timer])
return (
<>
<h1>Timer : {timer}</h1>
</>
);
}
export default App;
Please explain
You need to remove timer as dependency form the useEffect otherwise it will recreate another interval every time the timer gets updated.
You may also want to clear the interval using clearInterval in the cleanup of the hook i.e. when component unmounts (in this case).
And, as state updates may be asynchronous, you need to do setTimer(prev => prev + 1) to read the previous (the latest state) and increment to it.
function App() {
const [timer, setTimer] = React.useState(0)
React.useEffect(() => {
const id = setInterval(() => {
setTimer((prev) => prev + 1)
}, 1000)
return () => {
clearInterval(id)
}
}, [])
return <h1>Timer : {timer}</h1>
}
ReactDOM.render(<App />, document.getElementById('mydiv'))
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<body>
<div id="mydiv"></div>
</body>

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