# React Hook 📝
###### tags: `待補充` `React`
## useRef
## useContext
> Context provides a way to pass data through the component tree without having to pass props down manually at every level.
> 透過 useContext 可以將資料(state)直接傳到需要的 component 而不需要透過 props 一層層的傳遞下去。
#### React.createContext 創建
Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.
> The defaultValue argument is only used when a component does not have a matching Provider above it in the tree.
```javascript=
// 創建一個 Context 物件
import { createContext }
export const myContext = createContext();
```
#### Context.Provider 傳遞
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
```javascript=
// 建立需要被 Provider 傳遞下去的物件(也可以是陣列或單一資料,但物件的類別之後可以分別被使用,也比較有彈性)
const contextObject = {
state
setState
}
<myContext.Provider value={contextObject}>
<兒孫tags></兒孫tags>
</myContext.Provider>
```
#### 接收
```javascript=
import {useContext}
const { reRender } = useContext(timeblockDataContext);
```
### React 效能優化
###### tags: `useMemo` `useCallback`
> 在 React 中複雜的元件關係,如果沒有經過優化,將有可能會造成效能上的問題。
:::warning
在 Function Component 中,重新渲染 (re-render) 很輕易就會被觸發,少量的元件時還不會發生太大的問題,但是,如果遇到大型的網站平台,大量的元件不斷地被重新渲染,將會給瀏覽器重大的負擔,會造成使用者體驗不佳。
:::
如果父元件的狀態被改變了,但是 props 的結果沒有變,子元件仍然會被重新渲染。可是子元件的結果根本沒有改變,多餘的渲染造成性能上的浪費。
當父元件的 state 被改變了,但傳給子
#### `useMemo`
> 有複雜的計算但是不是每次都需要重新計算的時候。
#### `useCallback`
#### `useReducer`