Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – Updated prop in custom hook

I have a custom hook that gives me a certain percentage of the scroll. I takes the values from the state-management solution Zustand. I’m using it inside a component to update some styles on elements on the page.

The problem is that I only want to update these elements on a certain condition passed as prop of my component. And these conditions are not updated in my hook.

I don’t know how I should change it in order to get the updated condition.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import create from 'zustand'

const useStore = create(() => {
  scroll: 0
})

const useScroll = (callback: (scroll: number) => void): null => {
  const subscribe = useRef()

  useEffect(() => {
    if (subscribe & subscribe.current) {
      // Unsubscribe
      subscribe.current()
    }

    subscribe.current = useStore.subscribe(() => {
      callback(useStore.getState().scroll)
    })
  }, [subscribe])

  return null
}

const myComponent = (condition: Boolean) => {
  console.log(condition) // gives the updated value of the prop

  useScroll(() => {
    console.log(condition) // is not updated
  })
}

>Solution :

My guess is that you need to add the callback parameter to the list of properties useEffect is watching:

   useEffect(() => {
        ...
   }, [subscribe, callback])
   

That way, whenever the function callback changes because of a new condition, the useEffect will re-run.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading