'Question about stale variables in hook function

I am wondering if it is ok to replace a variable with a new one in a function using a hook function.

This may be a silly question but I have a function that could be constructed with values that could change. And I wanted to just pass in a function to construct the function variables that way it would be more reusable for my use case. But I am wondering if there are situations where this variable could turn up stale when trying to reference it. Are there any gotchas here that I need to be aware of?

Here is an example that I put together just using the window resize to initiate the changing of the variable. Note: this is just a very crude example of much more complex code.

const defaultOptions = {
  name: 'myFn',
  position: 0
}

const createCustom = (hookedOptions) => {
  let opts = {...defaultOptions, ...hookedOptions()}

  const onResize = () => {
    opts = opts = {...defaultOptions, ...hookedOptions()}
  }
  
  const useValue = () => {
    /// could maybe use opts value here
  }
  
  const get = () => opts
  
  window.addEventListener('resize', onResize)
  
  return {
    get
  } 
}

const box = document.querySelector('.box')
const hookFn = () => {
  const rect = box.getBoundingClientRect()
  return {
    position: rect.right
  }
}
const custom = createCustom(hookFn)

const log = () => console.log(custom.get())

document.querySelector('button').addEventListener('click', log)
.box{
  width: 10vw;
  height: 10vw;
  background: green;
}
<button>Button</button>
<div class="box"></div>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source