> For the complete documentation index, see [llms.txt](https://shenjunhong.gitbook.io/blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shenjunhong.gitbook.io/blog/yuan-ma/reacthook/usestate.md).

# useState

初步模拟让我们发现了Hooks的第一个核心原理：闭包，是的Hooks返回的state和setState方法，在hooks内部都是利用闭包实现的

## 用法

```jsx
  const defaultCount = props.defaultCount || 0;
  const [count, setCount] = useState(defaultCount)
  //useState 按照第一次返回的顺序给你state的
  
  return(
    <button onClick={()=>{ setCount(1)}}>
      Click({count})
    </button>
  )

```

## 原理

```js
let state:[any] = [];
let cursor: number = 0;
function useState<T>(initState: T): [T, (setState: T)=> void]{
  const currentCursor = cursor;
  state[currentCursor] = state[currentCursor] || initState;
  function setState(newState: T){
    state[currentCursor] = newState
    render()
  }
  ++cursor

  return [state[currentCursor], setState]
}
```

## 坑

1.useState 必须要规规矩矩的写

```js
 let name ,setName;
  let count , setCount;
  id+=1;

  if(id & 1){
     [count, setCount] = useState(0)
     [name, setName] = useState('Mike')
  } else {
     [name, setName] = useState('mike')
     [count, setCount] = useState(0)
  }
  ()=>{
    console.log('initial count')
    return props.defaultCount || 0;
  }
```

这样子写会有问题

在初始的状态是保存在一个全局变量中的, 多个状态,应该是保存在一个专门的全局容器中.

## 原理

```js
function resolvDispatcher(){
  var dispatcher = ReactCurrentOwner.currentDispatcher;
  !(dispatcher !== null) ? invariant(false, 'hook can only be ...');
  return dispatcher
}
```

这个方法真正用的时候 要在我们 react 进行渲染的时候， 已经创建虚拟 dom 的实例

```js
const queue = workInProgressHook.baseUpdate

// 接着我们判断
updateExpirationTime < renderExpriationTime


if(!didShip){
  newBaseUpdate = prevUpdate;
  newBaseState = _newState;
}

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://shenjunhong.gitbook.io/blog/yuan-ma/reacthook/usestate.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
