React has completely changed the way we build user interfaces, and one of its most powerful features is Hooks. In this post, we’re diving into two of the most essential React Hooks: useState and useEffect.

If you’re just getting started with React, or if you’ve only worked with class components before, this guide is for you.

What are Hooks?

Hooks are special functions that let us “hook into” React features from functional components. Before hooks, managing state or lifecycle methods meant writing class components. But with hooks, we can use those features directly inside functional components — making our code cleaner and more readable.

Why useState and useEffect?

Think of useState as the way we manage data that changes over time — like a counter, a form input, or a toggle.

And useEffect? That’s our tool for handling side effects — fetching data, setting up subscriptions, or manually changing the DOM.

Getting Started with useState

Let’s start with the most basic hook: useState.

What it does:

  • Initializes a state variable.
  • Lets us update that variable.
  • Re-renders the component when the state changes.
import React, { useState } from 'react';

function Counter() {
  // Declare a state variable called 'count' and set its initial value to 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Understanding useEffect

While useState manages data, useEffect manages behavior — what should happen when our component mounts, updates, or unmounts.

import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    // Cleanup function
    return () => clearInterval(interval);
  }, []); // Empty array means run only once (on mount)

  return <h1>Timer: {seconds}s</h1>;
}

Best Practices

Here are a few tips we follow when working with hooks:

  • Always declare hooks at the top level of the component.
  • Avoid using hooks inside conditions or loops.
  • Name state variables clearly — make your code easy to read.

Conclusion

Hooks like useState and useEffect make it easy to write functional components that are powerful, reusable, and clean. They’re the foundation for nearly every modern React app we build, and they’re essential knowledge for any React developer.

In the next post, we’ll explore more advanced hooks like useContext, useReducer, and custom hooks that let us extract logic into reusable functions.

Leave a Reply

Your email address will not be published. Required fields are marked *