UseState() Hook
Introducing Hooks
What was the motivation for introducing Hooks?
- React needs a better primitive for sharing stateful logic.
- Components that started out simple grew into an unmanageable mess of stateful logic and side effects.
- Each lifecycle method often contains a mix of unrelated logic, however, the same method might also contain some unrelated logic that sets up event listeners. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
- In many cases it’s not possible to break these components into smaller ones because the stateful logic is all over the place.
- It’s difficult to test.
- Using a separate state management library often introduces too much abstraction, requiring one to jump between different files, and making reusing components more difficult.
- Classes can be a large barrier to learning React. You have to understand how this works in JavaScript, which is very different from how it works in most languages.
- You have to remember to bind the event handlers.
What changes are important regarding implementing Hooks versus Component Classes? The major difference between Hooks and class-based state is that hooks are used inside of the functional component. Hooks should always be on the top level.
Hooks allow you to reuse stateful logic without changing ___ _______. …the component hierarchy
hooks api
Name two rules imposed by React Hook usage.
- 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 Hooks from regular JavaScript functions.
How would you identify a custom Hook and why might you create one? Hooks are appropriate when one wishes to to reuse stateful logic, not state itself.
the state hook
What is a Hook? Hooks allow one to use state and other React features without writing a class.
When would I use the useState Hook? useState() is a hook that allows you to play with state in functional components in react.
If you were to add React state to a function component by declaring a state variable: What does calling useState do? It declares a “state variable”. useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.
What do we pass to useState as an argument? The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need.
What does useState return? It returns a pair of values: the current state and a function that updates it.