โThe best way to understand something is to break it down to its simplest form.โ
React Hooks were introduced in React 16.8, changing how we write components forever. They allow you to use state and lifecycle features without writing a class. Letโs explore them in a beginner-friendly, practical way.
๐ง Why Hooks?
Before Hooks, you had to use class components to manage state and side effects. With Hooks, functional components became just as powerful โ and a lot cleaner.
โSimplicity does not precede complexity, but follows it.โ โ Alan Perlis
๐ง Commonly Used Hooks
1.
useState()
โ State in Functional Componentsconst [count, setCount] = useState(0);
It returns a stateful value and a function to update it.
2.
useEffect()
โ Side Effects (e.g., API calls, DOM updates)useEffect(() => { console.log("Component mounted or updated"); }, [dependency]);
Think of it as
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
in one.3.
useContext()
โ Access Global Data (without prop drilling)const theme = useContext(ThemeContext);
It helps you consume values from React Context easily.
4.
useRef()
โ Mutable Values That Persistconst inputRef = useRef(null);
Itโs useful for accessing DOM nodes or keeping mutable variables that donโt trigger re-renders.
5.
useReducer()
โ Advanced State Managementconst [state, dispatch] = useReducer(reducer, initialState);
Great for complex state logic, often used with global state tools.
๐ฏ Custom Hooks โ Reusable Logic
You can build your own hooks to reuse logic between components.
function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return width; }
โDonโt Repeat Yourself โ make a custom hook instead.โ โ Every React Dev
โ Final Thoughts
React Hooks make code cleaner, reusable, and easier to reason about.
Once you master them, your productivity as a React developer skyrockets ๐โHooks are not magic. Theyโre just functions โ but really powerful ones.โ
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)