- Web Dev Everyday
- Posts
- Web Dev Everyday - 18th September 2024🖥️
Web Dev Everyday - 18th September 2024🖥️
Daily dose of web dev
Welcome to Web Dev Everyday – your daily dose of 3 minute web development emails.
🚨🚨🚨 Announcement
Our repo Link → got a huge update!
30 coding questions with instructions, hints, examples, requirements.
Those questions represent coding questions which will be available in the Codetive app we are building.
Ranging from beginner (Toggle Dark/Light mode) to expert (implement rate limiting or build mini CSS library)
Screenshot of example question:
Free resource 😀 Link is here: Link →. If it’s useful, please star the repo, it will help us out a lot.
Let's dive in!
🎯 Tip of the day
6 react hooks mistakes beginner make
1. Avoid Using State When Not Necessary
If a component doesn't need to re-render on data change, use refs or access form data directly instead of state.
// Using refs instead of state
const emailRef = useRef();
function handleSubmit(e) {
e.preventDefault();
const email = emailRef.current.value;
// Use email value as needed
}
<input ref={emailRef} type="email" />
2. Use Functional Updates with useState
When updating state based on the previous state, use the functional form to ensure correct updates.
// Correctly updating state based on previous state
setCount((prevCount) => prevCount + amount);
3. Remember That State Updates Are Asynchronous
State changes don't update immediately; use useEffect
to perform actions after state updates.
const [count, setCount] = useState(0)
const increment = () => {
setCount(prev => prev + 1);
console.log(count)
}
increment(); // console.log: 0, count: 1
increment(); // console.log: 1, count: 2
increment(); // console.log: 2, count: 3
// so better to use:
useEffect(() => {
console.log(count); // Logs updated count accurately
}, [count]);
4. Avoid Unnecessary useEffect
Compute derived data directly during rendering to prevent extra re-renders.
// ❌ Wrong
// Knowing hooks does not mean you should always use them
const [fullName, setFullName] = useState('');
useEffect(() => setFullname(`${firstName} ${lastName}`);
// ----
// ✅ Correct
// Directly computing derived data without useEffect
// Simplicity wins :)
const fullName = `${firstName} ${lastName}`;
5. Be Mindful of Referential Equality Use useMemo
to memoize objects or functions and prevent unnecessary re-renders due to new references.
const person = useMemo(() => ({ age, name }), [age, name]);
useEffect(() => {
console.log(person);
}, [person]);
6. Clean Up Event Listeners in useEffect
Always return a cleanup function in useEffect
when adding event listeners to prevent memory leaks
useEffect(() => {
const handleResize = () => {
console.log('Window resized');
};
window.addEventListener('resize', handleResize);
// Cleanup event listener
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);