DEV Community

Lumin
Lumin

Posted on

6

บันทึกความเข้าใจ Redux Toolkit

ใครๆก็รู้ว่า redux มี store, reducer และ action

  • store มีหน้าที่ dispatch action
  • reducer เก็บ logic ที่จะเปลี่ยนแปลง state ที่เราสนใจ ตามประเภทของ action ที่กำหนด โดยอ้างอิงกับ state
  • action คือ constant ที่เรากำหนดสำหรับ component นั้นๆ

ตัวอย่างการเขียน redux แบบบ้านๆ

function counter(state, action) {
  if (typeof state === 'undefined') {
    return 0
  }

  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

var store = Redux.createStore(counter)

document.getElementById('increment').addEventListener('click', function() {
  store.dispatch({ type: 'INCREMENT' })
  // state = 1
})
Enter fullscreen mode Exit fullscreen mode

จากตัวอย่าง

  • counter() คือ reducer ที่คอยรับ action
  • action มี INCREMENT และ DECREMENT
  • เมื่อสั่ง dispatch({ type: INCREMENT }) เลยทำให้ state มีค่าเท่ากับ 1

จากตัวอย่างข้างบน จะเห็นว่ามันอาจจะเกิดปัญหาบางอย่างในการเขียน เช่น ใช้ action ผิด, ไม่รู้ว่า action มีอะไรบ้าง, เขียนเยอะ ฯลฯ

ณ จุดนี้ เราสามารถใช้ redux-toolkit แก้ปัญหาได้ ดังนี้

export const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: state => state + 1,
    decrement: state => state - 1
  }
})

const store = configureStore({
  reducer: counterSlice.reducer
})

document.getElementById('increment').addEventListener('click', () => {
  store.dispatch(counterSlice.actions.increment())
  // state = 1
})
Enter fullscreen mode Exit fullscreen mode

จากตัวอย่างของการใช้ createSlice จะเห็นว่า แค่ import counterSlice มาสร้าง store
เราก็สามารถใช้ action ได้จาก counterSlice.actions ซึ่งก็จะ list มาเฉพาะตัวที่ระบุไว้ ไม่ต้องเดาหรือไปดูใน code

น่าเอาไปใช้ในโปรเจคอื่นๆเนอะ ลดบรรทัดลงไปเยอะ

Note

  1. เรียบเรียงจาก: Basic Redux Toolkit Tutorial
  2. Redux Toolkit github, npm

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
sutthiej profile image
sutthiej

ดูจากแหล่งอื่น อธิบายไม่รู้เรื่องเลย ดูที่นี่ กระจ่างเลย

Collapse
 
ilumin profile image
Lumin

ขอบคุณมากครับ :D

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay