React useDefault hook

React, Hooks, State · Oct 23, 2021

Creates a stateful value with a default fallback if it's null or undefined, and a function to update it.

  • Use the useState() hook to create stateful value.
  • Check if the value is either null or undefined.
  • Return the defaultState if it is, otherwise return the actual value state, alongside the setValue function.
const useDefault = (defaultState, initialState) => {
  const [value, setValue] = React.useState(initialState);
  const isValueEmpty = value === undefined || value === null;
  return [isValueEmpty ? defaultState : value, setValue];
};

const UserCard = () => {
  const [user, setUser] = useDefault({ name: 'Adam' }, { name: 'John' });

  return (
    <>
      <div>User: {user.name}</div>
      <input onChange={e => setUser({ name: e.target.value })} />
      <button onClick={() => setUser(null)}>Clear</button>
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <UserCard />
);

More like this

  • React useMergeState hook

    Creates a stateful value, and a function to update it by merging the new state provided.

    React, Hooks · Sep 23, 2021

  • React useLocalStorage hook

    Creates a stateful value that is persisted to localStorage, and a function to update it.

    React, Hooks · Sep 13, 2021

  • React useSessionStorage hook

    Creates a stateful value that is persisted to sessionStorage, and a function to update it.

    React, Hooks · Sep 15, 2021