---
# System prepended metadata

title: '[第05堂] Hook'

---

# [第05堂] Hook

* **useState**
 >建立兩個空 array 分別存放 state 以及 setters

```javascript=
const [state, setState] = useState(initialState);
```

* **useEffect**
>useEffect 有兩個參數，第一個參數是函式，第二個參數則是陣列。

```javascript=
useEffect(()=>{},[]);

useEffect(() => {
     // 畫面渲染時會執行的function
    
    return () => {
     // 關閉頁面前會執行的function (在component 即將卸載前觸發)
    };
     
});
```

* **useLocation**
```javascript=
const location = useLocation();
```
* **useHistory**
```javascript=
const history = useHistory();
history.goBack();
history.push("/");
```
* **useNavigate**
```javascript=
const navigate = useNavigate();
navigate("/login");
```
* **useParams**
```javascript=
const params= useParams();
```
* **useSearchParams**
```javascript=
const [searchParams,setSearchParams]= useSearchParams();

const changeSearchParams=()=>{
    setSearchParams({ id:"1",  page:"10" })
    // url=/detail?id=1&page=10
}

return (
    <div>
        <div>編號 ：{searchParams.get("id")}</div>
        <button onClick={changeSearchParams}>修改</button>
    </div>
)
```


