DP
Kembali ke Tutorial
ReactPemula

Memahami React Hooks dari Nol

Pelajari useState, useEffect, useContext, dan custom hooks dengan contoh nyata yang mudah dipahami.

3 menit baca28 Mei 2026oleh Reza Maulana

Memahami React Hooks dari Nol

React Hooks adalah fitur yang diperkenalkan di React 16.8 yang memungkinkan kita menggunakan state dan lifecycle features tanpa harus menulis class component. Dalam tutorial ini, kita akan belajar hooks yang paling sering dipakai.

Apa itu Hooks?

Hooks adalah fungsi spesial yang memungkinkan kita "hook into" React features. Dengan hooks, kita bisa:

  • Menggunakan state di functional component
  • Menjalankan side effects
  • Mengakses context
  • Dan masih banyak lagi

useState - State Management

useState adalah hook paling dasar untuk mengelola state di functional component.

jsx
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

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

Cara Kerja useState

  1. useState(0) menginisialisasi state dengan nilai 0
  2. Return array dengan 2 elemen: nilai state dan fungsi setter
  3. Setiap kali setCount dipanggil, component akan re-render

useEffect - Side Effects

useEffect digunakan untuk menjalankan side effects seperti fetching data, subscriptions, atau manual DOM manipulation.

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

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Fetch user data
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => {
        setUser(data);
        setLoading(false);
      });
  }, [userId]); // Re-run jika userId berubah

  if (loading) return <p>Loading...</p>;
  return <div>{user.name}</div>;
}

Dependency Array

  • [] - hanya run sekali saat mount
  • [userId] - run saat mount dan setiap userId berubah
  • Tanpa array - run setiap render (hati-hati!)

useContext - Global State

useContext memudahkan akses ke context tanpa perlu Consumer component.

jsx
import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  
  return (
    <button className={theme === 'dark' ? 'btn-dark' : 'btn-light'}>
      Click me
    </button>
  );
}

Custom Hooks

Kita bisa membuat hooks sendiri untuk reuse logic.

jsx
function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Penggunaan
function App() {
  const [name, setName] = useLocalStorage('name', 'Guest');
  
  return (
    <input 
      value={name} 
      onChange={(e) => setName(e.target.value)} 
    />
  );
}

Rules of Hooks

Ada 2 aturan penting:

  1. Hanya panggil hooks di top level - jangan di dalam loops, conditions, atau nested functions
  2. Hanya panggil hooks dari React functions - functional components atau custom hooks
jsx
// ❌ SALAH
function Bad() {
  if (condition) {
    const [state, setState] = useState(0); // Jangan!
  }
}

// ✅ BENAR
function Good() {
  const [state, setState] = useState(0);
  
  if (condition) {
    // Gunakan state di sini
  }
}

Kesimpulan

React Hooks membuat functional components lebih powerful dan mudah dibaca. Mulai dengan useState dan useEffect, lalu eksplorasi hooks lainnya seperti useReducer, useMemo, dan useCallback sesuai kebutuhan.

Latihan

Coba buat counter dengan fitur:

  • Increment dan decrement
  • Reset ke 0
  • Simpan count ke localStorage

Selamat belajar! 🚀

#react#hooks#javascript#frontend

Diskusi (0)

Silakan masuk terlebih dahulu untuk ikut berdiskusi

Login Sekarang