ReactJS Program to useMediaQuery Hook with Explanation
ReactJS
Hard
Hooks & Effects
28 views
1 min read
85 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around hook, react, usemediaquery. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a hook that returns true/false based on a media query.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use matchMedia and listen to changes.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useEffect, useState } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(() => window.matchMedia(query).matches);
useEffect(() => {
const mql = window.matchMedia(query);
function onChange(e) {
setMatches(e.matches);
}
if (mql.addEventListener) mql.addEventListener('change', onChange);
else mql.addListener(onChange);
setMatches(mql.matches);
return () => {
if (mql.removeEventListener) mql.removeEventListener('change', onChange);
else mql.removeListener(onChange);
};
}, [query]);
return matches;
}
export default function App() {
const isSmall = useMediaQuery('(max-width: 600px)');
return (
<div style={{ padding: 16 }}>
<strong>meetcode layout</strong>
<div style={{ marginTop: 8, color: '#555' }}>Small screen: {isSmall ? 'Yes' : 'No'}</div>
</div>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create a hook that returns true/false based on a media query.
Input / Output
Output
Render a React component.
Constraints
Use matchMedia and listen to changes.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
import React, { useEffect, useState } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(() => window.matchMedia(query).matches);
useEffect(() => {
const mql = window.matchMedia(query);
function onChange(e) {
setMatches(e.matches);
}
if (mql.addEventListener) mql.addEventListener('change', onChange);
else mql.addListener(onChange);
setMatches(mql.matches);
return () => {
if (mql.removeEventListener) mql.removeEventListener('change', onChange);
else mql.removeListener(onChange);
};
}, [query]);
return matches;
}
export default function App() {
const isSmall = useMediaQuery('(max-width: 600px)');
return (
<div style={{ padding: 16 }}>
<strong>meetcode layout</strong>
<div style={{ marginTop: 8, color: '#555' }}>Small screen: {isSmall ? 'Yes' : 'No'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!