Member-only story
Understanding React State Hooks
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
When do you use hooks?
We call it inside a function component to add some local state to it. React will preserve this state between re-renders.
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.
What does useState return?
useState
returns a pair: the current state value and a function that lets you update it.
When can you use hooks?
You can call the function useState() from an event handler. It’s similar to this.setState
in a class, except it doesn’t merge the old and new state together.
If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a hook inside the existing function component.
Rules for Hooks
- Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
- Only call Hooks from React function components. Don’t call…