Implement a useDefault hook that returns the default value when state is null or undefined.

exportdefaultfunction Component() {
const initialUser = { name: 'Marshall' };
const defaultUser = { name: 'Mathers' };
const [user, setUser] = useDefault(defaultUser, initialUser);
return (
    <div>
      <div>User: {user.name}</div>
      <input onChange={(e) => setUser({ name: e.target.value })} />
      <button onClick={() => setUser(null)}>reset</button>
    </div>
  );
}

Arguments

Returns

The useDefault hook returns the same values as the useState hook.

Editorial

This hook is very similar to the useState hook, but it conditionally returns defaultValue as the first element of the returned tuple when the current state value is null or undefined.

Open files in workspace

import { useState } from "react";

export default function useDefault(defaultValue, initialValue) {
  const [value, setValue] = useState(initialValue);

  if (value === undefined || value === null) {
    return [defaultValue, setValue];
  }

  return [value, setValue];
}

If you're using TypeScript, this should be a warm up for you to start writing generic functions! To ensure that the inferred return type is a tuple and not just an array of unioned types, use as const or provide the explicit return type in the function signature.

Edge cases

You just have to be careful to not simply check for !value since 0 or false are also valid values for the state.