useDocumentTitle With Cleanup
ReactJS
Medium
5 views
Problem Description
Create a hook that sets document.title and resets it on unmount.
Output Format
Render a React component.
Constraints
Store previous title and restore it in cleanup.
Official Solution
import React, { useEffect, useState } from 'react';
function useDocumentTitle(title) {
useEffect(() => {
const prev = document.title;
document.title = title;
return () => {
document.title = prev;
};
}, [title]);
}
export default function App() {
const [count, setCount] = useState(1);
useDocumentTitle('meetcode step ' + count);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>Document title</h2>
<button type='button' onClick={() => setCount((c) => c + 1)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Next step</button>
<div style={{ marginTop: 10, color: '#555' }}>Check your browser tab.</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!