Introduction
Today, I explored two powerful React hooks: useContext
and useRef
. These hooks solve different problems in React apps, and understanding them can help you write cleaner and more efficient code.
Let me break down what I learned in simple terms.
useContext – Say Goodbye to Props Drilling!
Imagine you're passing data from a top-level component all the way down through several layers just to reach a deeply nested child. That's called props drilling — and it's messy!
useContext
helps avoid this. It allows you to share values like user data, theme, or language across your component tree without having to pass them manually at each level.
Example:
// Create a context
const UserContext = React.createContext();
function App() {
return (
<UserContext.Provider value="Tamilselvan">
<Profile />
</UserContext.Provider>
);
}
function Profile() {
return <Greeting />;
}
function Greeting() {
const user = React.useContext(UserContext);
return <h1>Hello, {user}!</h1>; // Outputs: Hello, Tamilselvan!
}
useRef – Keep Mutable Values Without Re-rendering
useRef
is a hook that gives you a place to store mutable values — values that can change — without causing re-renders.
Key Point:
Updating
useRef().current
does not trigger a re-render.
It’s commonly used for:
- Accessing DOM elements directly
- Keeping values like timers, previous props, or counters that don’t need to update the UI
Example:
import { useRef } from 'react';
function Counter() {
const countRef = useRef(0);
const handleClick = () => {
countRef.current += 1;
console.log("Clicked", countRef.current); // Logs the current count
};
return <button onClick={handleClick}>Click Me</button>;
}
Even though the value is changing, the component doesn’t re-render unless you use useState
.
Summary
Hook | Purpose | Triggers Re-render? |
---|---|---|
useContext |
Share data across components | ✅ Yes (when context value changes) |
useRef |
Store mutable data or DOM references | ❌ No |
Final Thoughts
Learning these hooks gave me a better understanding of how to manage data in a React app efficiently. useContext
helps with clean data sharing, while useRef
is perfect for mutable values you don't want to trigger UI updates.
Top comments (0)