Skip to main content

initializer function ↔ set value to result of calculation

pass function reference but do not invoke it with ()

pass Initializer Function as initial via reference - do not invoke

const [password, setPassword] = useState(genPassword);

...equivalent to

const [password, setPassword] = useState(() => genPassword());

NOT called with () else will call with render every time!!

// don't do this!
const [password, setPassword] = useState(genPassword());

must include necessary args to work!! else NaN !FAILS because no args passed

const CALC = {
ADD: (a, b) => a + b;
SUB: (a, b) => a - b;
};
function Calculator() {
const [calc, setCalc] = useState(CALC.ADD);
//...
}

initialize to methods via enum object - use arrow function to pass args

const CALC = {
ADD: (a, b) => a + b;
SUB: (a, b) => a - b;
};
function Calculator() {
const [calc, setCalc] = useState(() => CALC.ADD)
//...
}

References