( queries: string[], values: T[], defaultValue: T )
| 5 | } |
| 6 | |
| 7 | export const useMedia = <T>( |
| 8 | queries: string[], |
| 9 | values: T[], |
| 10 | defaultValue: T |
| 11 | ) => { |
| 12 | // Array containing a media query list for each query |
| 13 | const mediaQueryLists = isBrowser() |
| 14 | ? queries.map((q) => window.matchMedia(q)) |
| 15 | : []; |
| 16 | |
| 17 | // Function that gets value based on matching media query |
| 18 | const getValue = () => { |
| 19 | // Get index of first media query that matches |
| 20 | const index = mediaQueryLists.findIndex((mql) => mql.matches); |
| 21 | // Return related value or defaultValue if none |
| 22 | return values?.[index] || defaultValue; |
| 23 | }; |
| 24 | |
| 25 | // State and setter for matched value |
| 26 | const [value, setValue] = useState<T>(getValue); |
| 27 | |
| 28 | useEffect( |
| 29 | () => { |
| 30 | // Event listener callback |
| 31 | // Note: By defining getValue outside of useEffect we ensure that it has ... |
| 32 | // ... current values of hook args (as this hook callback is created once on mount). |
| 33 | const handler = () => setValue(getValue); |
| 34 | // Set a listener for each media query with above handler as callback. |
| 35 | mediaQueryLists.forEach((mql) => mql.addListener(handler)); |
| 36 | // Remove listeners on cleanup |
| 37 | return () => |
| 38 | mediaQueryLists.forEach((mql) => mql.removeListener(handler)); |
| 39 | }, |
| 40 | [] // Empty array ensures effect is only run on mount and unmount |
| 41 | ); |
| 42 | |
| 43 | return value; |
| 44 | }; |
no test coverage detected