null
or undefined
, and a function to update it.useState()
hook to create stateful value.null
or undefined
.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.render(<UserCard />, document.getElementById('root'));
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️