In my react app I have a hook that handles resizing of the screen. The function returns an array of width and height.
JavaScript
x
30
30
1
function useDimensions() {
2
const [size, setSize] = useState([window.innerWidth, window.innerHeight]);
3
const [isSmScreen, setIsSmScreen] = useState(false);
4
const [isLgScreen, setIsLgScreen] = useState(false);
5
6
function handleResize() {
7
const windowWidth = window.innerWidth;
8
if (windowWidth < BREAKPOINTS.sm) {
9
setIsXsScreen(true);
10
} else if (windowWidth < BREAKPOINTS.lg) {
11
setIsSmScreen(true);
12
}
13
14
setSize([window.innerWidth, window.innerHeight]);
15
}
16
17
useLayoutEffect(() => {
18
// So it doesnt get called every pixel changed
19
const debouncedResize = debounce(handleResize, 100);
20
21
window.addEventListener('resize', debouncedResize);
22
23
return () => window.removeEventListener('resize', handleResize);
24
}, []);
25
26
return size;
27
}
28
29
export default useDimensions;
30
And i call the hook in my react app like const [width] = useDimensions()
. I also want to call the hook like const {isSmScreen} = useDimensions()
. Is this possible and how can export it from the useDimensions hook
Advertisement
Answer
Sure, as an array is an object, you can define additional properties.
For instance:
JavaScript
1
3
1
size.isSmScreen = isSmScreen;
2
return size;
3
Or:
JavaScript
1
2
1
return Object.assign(size, {isSmScreen});
2
Whether this is a good idea, is debatable though. If I use a function to get an array, I would not expect that array to have other custom properties.
It would be more natural to return the array data as a single property of the returned object, like:
JavaScript
1
2
1
return { size, isSmScreen }
2
Then the caller must of course be aware of that. To only get the width, it could do:
JavaScript
1
2
1
let { size: [width] } = useDimensions();
2