E
E
eugenedrvnk2020-10-10 18:13:53
React
eugenedrvnk, 2020-10-10 18:13:53

What is the equivalent of Vue.mixin in React?

When writing projects in Vue, I quite often resorted to using a plugin (which was a global mixin) to get screen sizes. That is, I could use this.windowWidth and this.windowHeight anywhere in the application and it was as convenient as possible.

Now there is a need to do something similar in React. I originally wrote a hook that dynamically returns the window dimensions:

import {useState, useEffect} from 'react'

export const useWindowSize = () => {
  const [size, setSize] = useState({
    width: window.innerWidth, 
    height: window.innerHeight
  })

  const updateWindowSize = () => {
    setSize({
      width: window.innerWidth, 
      height: window.innerHeight
    })
  }

  useEffect(() => {
    window.addEventListener('resize', updateWindowSize)

    return window.removeEventListener(updateWindowSize)
  }, [])

  return size
}


And in principle, it can be used, but if you import it into each component, then, conditionally, if there are such 5 components, I will duplicate the hanging of the listener on resize 5 times. What are the convenient and neat options for solving such a situation, so that these window sizes would be calculated in one place and then used everywhere?

So far, on my part, it seems like the most correct solution would be to create a context with a name in the spirit of WindowSize in the root of the application, use this hook for screen sizes in it, and then, where necessary, import and use this context. But then, how can one avoid constant writing in the spirit of:

import WindowSize from './WindowSize';
const {width, height} = useContext(WindowSize)


Because a view option with the fact that you don’t need to import anything, but just take and use this.windowWidth will be more convenient :(

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question