Added a change in the color of the appbar when scrolling, but the problem is that the useEffect changes the data array. Every time the color of the appbar changes, the array itself changes.
Can it be rewritten in some other way?
const colorChange = useCallback(() => {
if (window.scrollY >= 200) {
setColor(true)
} else {
setColor(false)
}
}, [])
useEffect(() => {
window.addEventListener('scroll', colorChange)
return () => window.removeEventListener('scroll', colorChange)
}, [colorChange])
The function I use for random arrays
import _ from 'lodash'
export const shuffle = (array) => {
const random = _.shuffle(array)
return random.slice(0, 2)
}
CodePudding user response:
You don't have to pass colorChange in dependencies of the useEffect. no need for the useCallback. you can define a function inside the useEffect only.
useEffect(() => {
const colorChange = () => setColor(window.scrollY >= 200);
window.addEventListener("scroll", colorChange);
return () => window.removeEventListener("scroll", colorChange);
}, []);
CodePudding user response:
I found the answer. With ref data no longer changes due to scrolling.
I am attaching the solution:
import React, {useEffect, useRef, useState} from 'react'
const ref = useRef()
const [color, setColor] = useState(false)
ref.current = color
useEffect(() => {
const colorChange = () => {
const show = window.scrollY >= 200
if (ref.current !== show) {
setColor(true)
}
}
window.addEventListener('scroll', colorChange)
return () => window.removeEventListener('scroll', colorChange)
}, [])
