I am trying to maintain a value of an array, arr
, in a react component and I do not want a new array to be created with every render. That is because, I am setting arr
as a dependency in useMemo()
, and I do not want the callback function in useMemo
to execute unless the actual values contained in arr
change. However, what is actually happening and I want to prevent is that with every render, the callback function is executed. I thought of moving this array to be part of the props, is that correct?
let arr = ["name","age","degree"]
useMemo(() => {
//callback that get executed
}, arr)
You can use the useState hook to initialize the array and keep the value unless you use the setter to modify it.
const [arr, setArr] = useState(["name","age","degree"])