> For the complete documentation index, see [llms.txt](https://cyrilluce.gitbook.io/saga-duck/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cyrilluce.gitbook.io/saga-duck/api/utils.md).

# Utils

## useDuck <a href="#init--end" id="init--end"></a>

使用hook的方式快速在组件中使用Duck

```typescript
import { useDuck, Duck } from 'saga-duck'

function MyComponent(){
    const { duck, store, dispatch } = useDuck(Counter)
    const { selector, creators } = duck
    return <>
        Clicked: {selector(store).count} times
        <button onClick={() => dispatch(creators.increment())}>+</button>
    </>
}
```

## purify(FSC): DuckComponent <a href="#purify" id="purify"></a>

提供FSC的性能优化，更多可参考 [进阶-FSC优化](https://cyrilluce.gitbooks.io/saga-duck/content/advance.html#fsc)

```typescript
import { purify } from 'saga-duck'
export default purify(function DuckComponent({ duck, store, dispatch }){ ... })
```

## ~~memorize( (duck, dispatch)=>Mixed ): (instance|Props)=>Mixed~~ <a href="#memorize" id="memorize"></a>

**对于React16+，使用useMemo替代**

提供仅基于duck与dispatch的持久化，用于固定例如回调等函数的实例，阻止重复渲染，优化性能。

更多可参考 [进阶-其它通用的React优化](/saga-duck/jin-jie.md)

```typescript
import { memorize } from 'saga-duck'
const getHandler = memorize((duck, dispatch) => ()=>dispatch(duck.creators.bar()) )

function Container(props){
    const handler = gethandler(props)
    return <Foo handler={handler} />
}
```

### ~~asResult(selector, yield select(selector))~~ <a href="#asresultselector-yield-selectselector" id="asresultselector-yield-selectselector"></a>

因为generator过于灵活，以至于typescript对redux-saga的支持并不好，我们无法取得`yield select(selector)`正确的返回结果类型，这时可以使用`asResult`工具方法，它**不做任何操作**原样返回结果，供typescript正确识别返回类型。

```typescript
import { asResult } from 'saga-duck'

function* saga(k){
    const myState = asResult(this.selector, yield select(this.selector))
    // now myState is the type of duck.selector's return type
}
```

在经过实践后，**不再推荐使用**（尽管它是redux-saga官方的推荐写法），而是直接用下面的方式，能直接取得类型信息

```typescript
const myState = this.selector(yield select())
```

### reduceFromPayload / createToPayload <a href="#reducefrompayload--createtopayload" id="reducefrompayload--createtopayload"></a>

通常情况下，saga-duck中的大部分reducers及actionCreators都是极其简单并雷同的

```typescript
let reducer = (state=0, action): number=>{
  switch(action.type){
    case types.SET_ID:
      return action.payload
    default:
      return state
  }
}
let creator = (id: number)=>({ type: types.SET_ID, payload: id })
```

我们可以将它简化成这样

```typescript
import { reduceFromPayload, createToPayload } from 'saga-duck'

let reducer = reduceFromPayload(types.SET_ID, 0)
let creator = createToPayload<number>(types.SET_ID)
```
