loading...

Try useStateOnce if you are about to init a heavy state

fantasticsoul profile image 幻魂 ・1 min read

star me if you like it, thx.

motivation

upgrade react useState hook, let the state been initialized only one time, hope you guys like it.

traditional useState

import React, { useState } from "react";

function Demo() {
  // if user pass a heavy state to useState
  // this state will been initialized in every render period
  const [heavyState] = useState(Array(1000000));
  return <h3>{heavyState.length}</h3>;
}

with useStateOnce

useStateOnce accept normal state or function state
if user pass function state to useStateOnce, it will only been called one time
so user can completely replace React.useState with useStateOnce

import React from "react";
import useStateOnce from "use-state-once";

const state = () => {
  console.log("this function will only been called one time");
  return Array(1000000);
};

function Demo() {
  // useStateOnce accept normal state or function state;
  // if user pass function state to useStateOnce, it will only been called one time
  const [heavyState, setHeavyState] = useStateOnce(state);
  return <h3>{heavyState.length}</h3>;
}

Concent also provide this ability

Concent's api useConcent also have the same effect with useStateOnce when user pass a private state to it;

you can also open the SandBox, and copy the other file's content to file App.js to see the more concent funny features.

Discussion

pic
Editor guide
Collapse
calag4n profile image
calag4n

Pretty cool hook 👍️, thanks 幻魂.

Collapse
fantasticsoul profile image
幻魂 Author

Thank you for your reply so much, actually I've written a concent version todo-list with hook useConcent

concent todo mvc vs redux&hook todo mvc

you may get some ideas from these two examples.