Dev to webs {Coding…}

บทเรียนฟรีด้านการพัฒนาซอฟต์แวร์ ที่ครอบคลุมเนื้อหาหลากหลาย ตั้งแต่การเขียนโค้ดพื้นฐานไปจนถึงเทคนิคขั้นสูง

Hook คืออะไร?

Hook เป็นฟีเจอร์ใน React ที่ช่วยให้นักพัฒนาสามารถใช้งานฟีเจอร์ต่างๆ ของ React (เช่น state และ lifecycle methods) ใน Functional Components ได้ โดยไม่จำเป็นต้องใช้ Class Components

คุณสมบัติเด่นของ Hook:

  • ช่วยให้ Functional Components มีความสามารถเหมือน Class Components
  • ช่วยให้โค้ดกระชับและอ่านง่าย
  • สามารถใช้ร่วมกับ Hooks อื่นๆ ที่สร้างเองได้ (Custom Hooks)

ประโยชน์ของการใช้ Hook:

  1. จัดการ State: ใช้ useState เพื่อเก็บและอัปเดตข้อมูล
  2. จัดการ Side Effects: ใช้ useEffect เพื่อทำงานเมื่อ Component มีการโหลดหรือเปลี่ยนแปลง
  3. เขียนโค้ดที่ยืดหยุ่นและนำกลับมาใช้ใหม่ได้ง่าย: สามารถสร้าง Custom Hook ที่ปรับใช้กับโปรเจกต์ต่างๆ

ประเภทของ Hook ที่สำคัญ

  1. useState
    • ใช้สำหรับจัดการ State ใน Functional Components
    • ตัวอย่าง
1
2
3
4
5
6
7
8
9
10
11
12
import React, { useState } from 'react';
 
const Counter = () => {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
};

2. useEffect

  • ใช้สำหรับจัดการ Side Effects เช่น การดึงข้อมูล การ subscribe หรือการอัปเดต DOM
  • ตัวอย่าง:javascriptคัดลอกโค้ด
1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { useEffect, useState } from 'react';
 
const DataFetcher = () => {
  const [data, setData] = useState(null);
 
  useEffect(() => {
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []); // Empty array: ทำงานครั้งเดียวหลัง Component mount
 
  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};

3. useContext

ใช้เพื่อเข้าถึงค่า Context โดยไม่ต้องใช้ Context.Consumer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React, { createContext, useContext } from 'react';
 
const MyContext = createContext('Default Value');
 
const Child = () => {
  const value = useContext(MyContext);
  return <p>Context Value: {value}</p>;
};
 
const App = () => {
  return (
    <MyContext.Provider value="Hello Hook!">
      <Child />
    </MyContext.Provider>
  );
};

4.useReducer

ใช้จัดการ State ที่มีความซับซ้อนหรือมีหลาย action

ตัวอย่าง

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React, { useReducer } from 'react';
 
const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
};
 
const Counter = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
 
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
};

ข้อควรรู้เกี่ยวกับ Hook:

  • Hook สามารถใช้ได้เฉพาะใน Functional Components หรือ Custom Hook
  • Hook ต้องเรียกใช้นอกฟังก์ชันใดๆ (เช่น ลูปหรือเงื่อนไข)
  • React มีการตรวจสอบ “Rules of Hooks” เพื่อป้องกันข้อผิดพลาดในการใช้งาน