41
loading...
This website collects cookies to deliver better user experience
useState
, useMemo
and useRef
. We're going to see which one is the best way to create real constants (not constant-like values).useConst
hook from chakra-ui in a previous post, and I recently found the same hook in Fluent UI so we are going to see why they've implemented it.useMemo
hook. This is a good option, but only if your "constant" value shouldn't change based on the dependencies.const memoizedValue = useMemo(
() => computeExpensiveValue(a, b),
[a, b]
);
useMemo
is always the same even when the dependencies didn't change. For this reason React runs the factory function if the tool believes that the value should be re created.Write your code so that it still works without useMemo
— and then add it to optimize performance.
const [value] = useState(initialValue);
useState
but it's expensive due to reducer handling which we don't need.useRef
hook can hold a value, and it neither has an internal reducer nor checks on the dependencies array. Also, React doesn't re-create the value for performance reasons.const useConst = (initialValue) => {
const ref = React.useRef();
if (ref.current === undefined) {
ref.current = typeof initialValue === 'function' ? initialValue() : initialValue;
}
return ref.current;
}
useState
to create constants because it's expensive.useMemo
is for you (but your code should still work without this hook).useRef
is the solution that you need, and remember that some libraries like Chakra UI or Fluent UI provides a built-in useConst
for this.