iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
Modern Web

關於React,那些我不知道的系列 第 27

不用Recoil的話,如何自己製作一個 Custom hook 來共享全域變數?

需求

在早前幾篇文章,我們介紹了 Recoil 這個 library 來在整個 App 分享全域變數給所有元件使用。

// React hook
const [count, setCount] = useState(initialCountState)
// Recoil
const [count, setCount] = useRecoilState(countState)
// custom hook
const [count, setCount] = useMyCustomHook()

解決方案

這是一個混合應用,思考看看我們需要哪些技術可以使用

首先,回想到之前的 React hook ,如何獲取全域變數,我們有提到 useContext ,可參考之前 實現跨元件資料共享, useContext

  1. useContext [因為要跨元件共享]
  2. useState [要能 read / write 一組狀態 (count, setCount)]
  3. custom hook...?

何謂 custom hook

可以參考
1.【React.js入門 - 24】 Custom hook - 給我另一個超推React hook的理由
2..【Day.25】React進階 - Custom hook | 把React API模組化吧!
3.[Day 25 - 即時天氣] 自己的鉤子自己做 - 建立 Custom Hook

接著讓我們一起來解決這個需求吧!!!


上一篇
Modal in React ( Declarative Modal ) (2)
下一篇
不用Recoil的話,如何自己製作一個 Custom hook 來共享全域變數?(2)
系列文
關於React,那些我不知道的30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言