Skip to content

Mutable THREE objects should retain their values in useState #145

Closed
@takuma-hmng8

Description

@takuma-hmng8

useRefuseStateも、初期値に関数の実行結果を渡すと、レンダリングのたびに実行してしまう。遅延初期化関数を使うことで回避できる

const testing = (log: string) => {
   console.log("初期化:" + log);
   return log;
};

export const Test = () => {
   const [count, setCount] = useState(0);

   const testRef = useRef(testing("useRef:" + count));
   const [testState] = useState(testing("useState:" + count));
   const [testState2] = useState(() => testing("useState2:" + count));

   return (
      <div>
         <p>state:{count}</p>
         <p>testRef:{testRef.current}</p>
         <p>testState:{testState}</p>
         <p>testState2:{testState2}</p>
         <button onClick={() => setCount((prev) => prev + 1)}>click</button>
      </div>
   );
};

この例では、 const [testState2] = useState(() => testing("useState2:" + count));以外は、setCountのたびにtestingを実行する

ミュータブルなTHREEオブジェクトはuseStateで値を保持するべき

const [scene] = useState(() => new THREE.Scene());

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions