skip to Main Content

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


  1. You could just set your state to empty, set your array, get the length, then set state to array.

    const [myArray, setMyArray] = useState([]);
    
    const tempArr = ["Some Value", "Some other value"]
    const myArrayLength = tempArr.length; 
    setMyArray(tempArr);
    
    ...
    ...
    
    setMyArray([ ...myArray, "add a value"]);
    
    Login or Signup to reply.
  2. I think you can use useRef to hold the length of your array. Compare and update its value when needed without causing any rerender.

    When to use useRef() instead of useState()

    A rule of thumb is to use useState when you need to re-render the
    component when the state changes and useRef when you don’t need to
    re-render the component when the state changes. Here are some examples
    of when to use useRef instead of useState:

    • When you need to store a value that does not trigger a re-render when
      it is updated.
    • When you need to store a value that is not used in the
      render method.
    • When you need to store a value that persists for the
      lifetime of the component.

    Check out this link.

    Login or Signup to reply.
  3. If you’d like to run a function anytime myArray changes, you could use useEffect

    useEffect(() => { /* your code here */ }, [myArray])
    

    Notice the dependency array [myArray]. That tells React to run the effect if myArray is unequal to myArray from the previous render.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search