React Hooks:
- React Hooks allow function components to use state and other React features without writing a class component
- Hooks provide a more direct API to React features like props, state, context, refs, and lifecycle methods.
- Props => already available in function components, but hooks (like useContext) make them easier to consume from context.
- State => managed directly with useState instead of this.state in classes.
- Context => accessed with useContext.
- Refs => managed with useRef.
- Lifecycle => handled with useEffect instead of componentDidMount, componentDidUpdate, etc.
- You must import hooks from react.
Hooks Rules:
- Hooks can only be called inside of react function components.
- Hooks can only be called top level of components .
- Hooks can not be conditional.
useState Hooks:
- To use useState hooks we first need to import it into our component
- Hooks react allows functional components to manage and update component
- Call useState at the top level of your component to declare a state variable.
- The convention is to name state variables like
[user, setUser]
using array destructuring.
- useState returns an array with exactly two items:
- The current state of this state variable, initially set to the initial state you provided.
- The set function that you allows you to update the initial state value.
Top comments (0)