Reference useCallback

  • The same as useMemo, most occasion use useMemo.
  • Has to have a depency array.
  • Caches the reference of the previous state and will only run if the reference has changed!!
  • The difference to useMemo is useCallback returns the entire function!!!
  • Referential Equality: Only runs if the reference has changed.
1
2
3
WDS Video on this Hook
import React, { useState, useEffect, useCallback } from "react"; function ExampleUseCallback() { const [something, setSomething] = useState(1); const [dark, setDark] = useState(false); const example = useCallback(() => { return [something, something + 1, something + 2]; }, [something]); return ( <Stack alignItems={"center"} sx={{ width: "100%", maxWidth: "40dvw", margin: 2, backgroundColor: "lightblue", padding: 7, borderRadius: 15 }}> <TextField type="number" label="something" variant="outlined" value={something} onChange={(e) => setSomething(parseInt(e.target.value))} /> <Stack direction={"row"} alignItems={"center"} gap={5} sx={{ marginTop: 5 }}> <Button variant="contained" color={dark ? "primary" : "success"} onClick={() => setDark((d) => !d)}> Example </Button> </Stack> <Box sx={{ marginTop: 5 }}> <ListExample getItems={example} /> </Box> </Stack> ) }