useStateを独自に実装

 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"));
 }

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS