Skip to content

useDefault

Sets a default value to a state when it is null or undefined

The useDefault hook is helpful when you want to assign a default value to a state which is likely to be undefined or null in future.

It ensures that the state never reaches the undefined or null values.

useDefault

Current Value: 1

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import React from 'react';
import { useDefault } from '@abhushanaj/react-hooks';
function App() {
const [count, setCount] = useDefault(1, 0);
return (
<div>
<p>Current Value: {count}</p>
<button onClick={() => setCount((prev) => prev + 1)}>Increment by 1</button>
<button onClick={() => setCount((prev) => prev - 1)}>Decrement by 1</button>
<button onClick={() => setCount(null)}>Set to null</button>
<button onClick={() => setCount(undefined)}>Set to undefined</button>
</div>
);
}
export default App;

Properties

The defaultValue cannot be null or undefined.

In such cases, and error is throw with a message: Default value cannot be undefined or Default value cannot be null.

./src/App.tsx
function App() {
const [count, setCount] = React.useState(0);
// useDefault will throw an error message: `Default value cannot be undefined`
const previousValue = useDefault(count, undefined);
return <div>.....</div>;
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
initialValueInitialValues<T>The variable to keep track of.N/A
defaultValueTThe default value when state becomes null or undefined.N/A

Return Value

The hook returns the same signature of React.useState() hook. It is a tuple consistent of [state, stateUpdateFn]

ParameterTypeDescriptionDefault
stateTThe current state value.N/A
stateUpdateFnStateUpdateFnThe state updater function.N/A

Types Reference

1. InitialValues<T>

InitialValues<T>: T | null | undefined;

2. StateUpdateFn

React.Dispatch<React.SetStateAction<InitialValues<T>>>