I’m facing this issue in react:
I have an array in a state and I also need to track it’s length so that I can know when it’s been modified.
const [myArray, setMyArray] = useState(["Some Value", "Some other value"]);
const myArrayLength = myArray.length;
At some point in the code:
setMyArray([ ...myArray, "add a value"]);
console.log(myArray.length) // Output: 3
console.log(myArrayLength) // Output: Also 3!! - wish it stayed at 2
Ideally I would want the const myArrayLength to not change dynamically as the state of myArray changes so that I can track when myArrayLength !== myArray.length
I could create a whole new state: const [myArrayLength, setMyArrayLength] = useState(myArray.length);
and it would work
But it doesn’t feel right because I would never use the setter setMyArrayLength
Open to any ideas! Maybe I’m going about this whole thing the wrong way
EDIT :
Thank you all for your answers!
I think simply using them other hooks, useRef or useEffect to the rescue here makes the most sense.I was wondering if there was a way to avoid it but doesn’t look like it.
I might go with useRef because it’s a one liner, but useEffect to update the length in a new state also makes a lot of sense.
Only thing is it works using const myArrayLength=useRef(myArray.length)
, I just need to use myArrayLength.current
to get the value back
3
Answers
You could just set your state to empty, set your array, get the length, then set state to array.
I think you can use
useRef
to hold the length of your array. Compare and update its value when needed without causing any rerender.Check out this link.
If you’d like to run a function anytime myArray changes, you could use
useEffect
Notice the dependency array
[myArray]
. That tells React to run the effect if myArray is unequal to myArray from the previous render.