# Duck

## Define \`createReducer\` helper

```javascript
const createReducer = (initialState = {}, handlers = {}) => (state, action) => {
  const nextState = produce(state, draft => {
    if (handlers[action.type]) {
      return handlers[action.type](draft, action)
    }
  })

  return nextState
}
```

{% hint style="info" %}
`produce` is a function of [immer](https://github.com/immerjs/immer)
{% endhint %}

## Declare initial state

```javascript
const initialState = {
  locale: 'en',
  theme: 'light',
}
```

## Declare action types

```javascript
const types = new Proxy({
  CHANGE_LOCALE: 'CHANGE_LOCALE',
  CHANGE_THEME: 'CHANGE_THEME',
}, {
  get: (target, prop) => `app_name/domain_namespace/${target[prop]}`,
})
```

{% hint style="info" %}
prefix `app_name/domain_namespace` for separating your action from 3rd parties actions such as [connected-react-router](https://github.com/supasate/connected-react-router), [redux-saga](https://github.com/redux-saga/redux-saga) when working with redux devtools
{% endhint %}

## Declare action creators

```javascript
const actions = {
  changeLocale: newLocale => ({ type: types.CHANGE_LOCALE, payload: newLocale }),
  changeTheme: newTheme => ({ type: types.CHANGE_THEME, payload: newTheme }),
}
```

## Declare reducer

```javascript
const reducer = createReducer(initialState, {
  [types.CHANGE_LOCALE]: (draft, { payload }) => {
    draft.locale = payload
  },
  [types.CHANGE_THEME]: (draft, { payload }) => {
    draft.theme = payload
  },
})
```

## Declare selectors

```javascript
const selectors = {
  selectApp: state => state.app || initialState,
  makeSelectLocale() {
    return createSelector(this.selectApp, ({ locale }) => locale)
  },
  makeSelectTheme() {
    return createSelector(this.selectApp, ({ theme }) => theme)
  },
}
```

{% hint style="info" %}
`createSelector` is a function of [reselect](https://github.com/reduxjs/reselect)
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://valonekowd78.gitbook.io/tech-notes/react/duck.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
