Make mandatory to pass initial state in React.useState
See original GitHub issueRight now, it is possible to use hooks in order to set state for functional components as follows:
function Foo() {
const [state, setState] = React.useState();
}
There is no parameter passed to useState
above. If it is blank, React assumes it is undefined
. I think it would be an improvement to make it compulsory to pass a parameter to useState
. If it is supposed to be undefined, one should pass undefined
. Or at least, there should be a warning if one does not manually set initial state.
This will make the developers be aware of what initial state they have set. And also the blunders like const [state = initial, setState] = React.useState()
.
Proposed way of doing
function Foo() {
const [state, setState] = React.useState(initial);
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:10 (2 by maintainers)
Top Results From Across the Web
When to use useState initial value as function? - Stack Overflow
You use it when you want the computation of that initial state to happen only once. Because if you use an expression instead...
Read more >useState in React: A complete guide - LogRocket Blog
useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function and...
Read more >useState - React Docs
initialState : The value you want the state to be initially. It can be a value of any type, but there is a...
Read more >Understanding useState's initial value - Max Rozen
The key difference is that the initial value of the state defined by useState can be anything you want it to be. It...
Read more >How to use React useReducer hook like a pro - Devtrium
const [state, setState] = useState(initialValue); const [state, dispatch] = useReducer(reducer, initialValue);. As you can see, in both cases ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@TodorTotev if it is not explicitly stated, it is taken as
undefined
. Developers can manually setundefined
. But it would be a breaking change. Other than that, I don’t see a reason why that should be a problem – But I welcome the opportunity to learn why you think otherwise.But at the very least, warnings will be helpful.
Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!