Have you ever built a simple counter in React and thought there must be a better way to handle updates and side effects? I certainly have. When I first encountered the use of state and effects in React, it felt a little magical, and at times a bit opaque. In this short guide I will walk you through a hands‑on example that illustrates how state and effects play together, from the perspective of a developer who is not yet an expert but keen to level up.
Why State Matters
State lets you store values that change over time, for example a score in a game or the number of unread messages. In React you declare state in a function component with a hook. Here is a simple counter:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</div>
);
}
export default Counter;
Here the effect runs only when the count changes. That small addition demonstrates how React keeps the user interface and external systems in sync.
How It Flows
Let us look at a simple sequence diagram so you can picture what happens under the hood.
That diagram shows the chain of events from a user click to the effect that updates the document title.
Next Steps
Give this code a spin. Tinker with the dependency array of the effect hook and see what happens when you omit it or add other variables. Try adding a second effect that logs values to the console.
Top comments (0)