Using React Hooks (useState and useEffect)
Hooks, which come with React 16.8, eliminate the complex structure of class components, allowing you to create simpler and more powerful applications with functional components.
In this guide, you will learn how to manage state, lifecycle, and side effects using the useState and useEffect Hooks.
🯠What Will You Learn in This Guide?
- Manage component state with useState Hook
- Control the lifecycle with useEffect
- Pulling data from the API and unmounting components
- Performance optimization with dependency array
âš™ï¸ Prerequisites
- Basic knowledge of React and JavaScript ES6
- A project created with
create-react-app - Know the difference between functional and class components
1ï¸âƒ£ State Management with useState()
useState is the simplest way to add internal state to a component.
Now you can manage status with just a few lines of code, without dealing with complex structures like this.state or this.setState.
🔹 Basic Usage
import React, { useState } from 'react';
function SkorSayaci() {
const [sayi, setSayi] = useState(0);
return (
<div>
<h1>{sayi}</h1>
<button onClick={() => setSayi(sayi + 1)}>Sayacı Arttır</button>
</div>
);
}
useState(0) creates a state with an initial value of 0. The first element (number) of the returned array is the current value, and the second element (setNumber) is the update function.
🔹 Using Multiple useStates
You can define multiple state variables in the same component:
import React, { useState } from 'react';
function KullaniciGiris() {
const [kullaniciAdi, setKullaniciAdi] = useState('');
const [sifre, setSifre] = useState('');
return (
<form>
<label>
Kullanıcı Adı:
<input value={kullaniciAdi} onChange={e => setKullaniciAdi(e.target.value)} />
</label>
<br />
<label>
Şifre:
<input value={sifre} onChange={e => setSifre(e.target.value)} type="password" />
</label>
<button type="submit">Giriş Yap</button>
</form>
);
}
Each useState call manages different data; this makes the component more modular.
2ï¸âƒ£ Lifecycle and Side Effects with useEffect()
useEffect replaces the componentDidMount, componentDidUpdate, and componentWillUnmount methods in class components. This Hook manages side effects by running after each render.
🔹 Basic Usage
import React, { useState, useEffect } from 'react';
function SkorSayaci() {
const [sayi, setSayi] = useState(0);
useEffect(() => {
document.title = `Skor: ${sayi}`;
console.log("Yeni skor:", sayi);
});
return (
<div>
<h1>{sayi}</h1>
<button onClick={() => setSayi(sayi + 1)}>Arttır</button>
</div>
);
}
useEffect runs after each render where the browser title is updated.
3ï¸âƒ£ useEffect Dependency String: When Should It Work?
The dependency string ([]) can be added as a second argument to useEffect.
Empty string ([]) → Only works on first load.
Array containing value ([number]) → Only runs when the specified value changes.
useEffect(() => {
console.log("Bileşen ilk kez yüklendi.");
}, []); // sadece mount
useEffect(() => {
console.log("Sayı değişti:", sayi);
}, [sayi]); // sadece 'sayi' değiştiğinde
In this way, unnecessary renders are prevented and performance is maintained.
4ï¸âƒ£ Cleanup Procedures
When the component is unmounted, you can free resources by returning a function from useEffect.
useEffect(() => {
console.log("Bileşen aktif.");
return () => console.log("Bileşen kaldırıldı (unmounted).");
}, []);
This construct is the modern equivalent of componentWillUnmount.
5ï¸âƒ£ Pulling Data from API with useEffect
In React, you can use the fetch() function in useEffect to fetch data from an external API.
import React, { useState, useEffect } from 'react';
function GenixNodeKullanicilari() {
const [kullanicilar, setKullanicilar] = useState([]);
useEffect(() => {
fetch('https://api.github.com/users')
.then(res => res.json())
.then(data => setKullanicilar(data));
}, []);
return (
<div>
{kullanicilar.map(k => (
<div key={k.id}>
<h4>{k.login}</h4>
</div>
))}
</div>
);
}
Thanks to the empty array, this code will only run when the component is first loaded.
ðŸ™‹â™€ï¸ Frequently Asked Questions (FAQ)
- Why do hooks only work on functional components?
Because class components already have their own life cycle. Hooks give these features to functional components.
- Why do set functions in useState work asynchronously?
React groups state updates for performance. Therefore, the changes are reflected in the next render, not immediately.
- Should I add function to useEffect dependency array?
Yes, every variable or function defined outside within the Hook must be added to the dependency. This ensures consistent behavior.
- Can I write my own custom Hooks?
Yes. You can create your own useXXX Hook and reuse it across components.
- What is the difference between useEffect and useLayoutEffect?
useEffect runs asynchronously (after render). useLayoutEffect runs synchronously (just before rendering). If DOM measurement is required, useLayoutEffect is used.
🚀 Result
Now you can create powerful, simple and reusable components with React Hooks without the need for a class structure. useState handles state management, and useEffect handles the lifecycle in a single line.
💡 Test your application on the GenixNode Platform and go live instantly!

