useState & useMemo
Multiple Set State
Live Editor
function Example() { const [moo, setMoo] = useState(0); const [foo, setFoo] = useState(0); const handleClick = () => { setMoo(moo + 1) setMoo(moo + 1) // ??!! setFoo(foo + 1) } return ( <> <p> <button onClick={handleClick}>Click Me</button> </p> <p>Moo: {moo}</p> <p>Foo: {foo}</p> </> ); }
Result
Loading...
useState on Object
Live Editor
function Example() { const [counter, setCounter] = useState(0); const [animal, setAnimal] = useState('dog'); const obj = { type: (animal === 'dog') ? 'Mammals' : 'Bird', move: (animal === 'dog') ? 'walk' : 'fly' } // const obj = useMemo(() => ({ // type: (animal === 'dog') ? 'Mammals' : 'Bird', // move: (animal === 'dog') ? 'walk' : 'fly' // }), [animal]) const handleIncrease = () => { setCounter(counter => counter + 1) } const handleChange = () => { if (animal === 'dog') { setAnimal('duck') } else { setAnimal('dog') } } useEffect(() => { console.log('Obj changed', obj) }, [obj]) return ( <> <p> <button onClick={handleIncrease}>Increase</button> <button onClick={handleChange}>Change</button> </p> <p>Counter: {counter}</p> <p>{obj.type} can {obj.move}</p> </> ); }
Result
Loading...
useMemo
Live Editor
function Example() { const [expensive, setExpensive] = useState(0); const [cheap, setCheap] = useState(0); const somethingExpensive = (origin) => { let result = origin for (let i=0; i <= 1000000000; i++) { result += 0.000000001 } return result } const handleClickCheap = () => { setCheap(cheap + 1) } const handleClickExpensive = () => { setExpensive(somethingExpensive(expensive)) } return ( <> <p> <button onClick={handleClickCheap}>Cheap</button> <button onClick={handleClickExpensive}>Expensive</button> </p> <p>Cheap: {cheap}</p> <p>Exp: {expensive}</p> </> ); }
Result
Loading...
useCallback
useCallback(fn, [dep])
useMemo(() => fn, [deps])