#author("2021-03-19T03:46:13+09:00","default:ryuichi","ryuichi")
#author("2021-03-19T03:48:27+09:00","default:ryuichi","ryuichi")
* useStateを独自に実装 [#t5eced8b]

 import React from "react";
 import ReactDOM from "react-dom";
 
 let callCount = -1;
 let states = [];
 
 function useState(initialValue) {
   const id = ++callCount;
 
   if (states[id]) return states[id];
 
   const setValue = (newValue) => {
     states[id][0] = newValue;
     reRender();
   };
   let tuple = [initialValue, setValue];
   states.push(tuple);
   return tuple;
 }
 
 const MyComponent = () => {
   const [message, setMessage] = useState("");
   const [error, setError] = useState(false);
   return <div></div>;
 };
 
 const App = () => {
   return (
     <div>
       <MyComponent />
     </div>
   );
 };
 
 function reRender() {
   callCount = -1;
   ReactDOM.render(<App />, document.getElementById("root"));
 }

- コンポーネントの外側にstatesとcallCounterを持っている
- ifの中でuseState()してはいけないのは、reRender()のたびにuseState()したりしなかったりするとstatesの数や順番が変動することになり、reRender()する前のstatesの値と違ってしまうから
- だから、コンポーネント関数の先頭で必要な分だけまとめてuseState()するべき

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS