React useState Hook
React useState hook
React Hooks
Hooks let you use different React features from your components. You can either use the built-in Hooks or combine them to build your own.
React Hooks are functions whose names starts with use
.
built-in Hooks in React:
- State Hooks - remember information like user input.
- Context Hooks - receive information from top-level component
- Ref Hooks - let a component hold information that isn’t used for rendering, like DOM node or a timeout ID.
- Effect Hooks - Effects let a component connect to and synchronize with external systems. This includes dealing with network, browser DOM, animations, widgets written using a differnt UI library, and other non-React code.
- Performance Hooks - common way to optimize re-rendering performance by skipping unnecessary work.
- Resource Hooks - Resources can be accessed by a component without having them as part of their state. For example, a component can read a message from a Promise or read styling information from a context.
- Other Hooks - useDebugValue, useId and useSyncExternalStore
Rules of Hooks
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component.
useState Hook
state is like a component’s personal data storage.
Properties are read only, so it cannot hold information that changes. React provide states to keep track of the state of the component. A state can be number, string, javascript object or array.
useState
is a Hook that lets you add React state to function components. useState returns a paire of values, the current state and a function to update the value.
To import useState
1 | import React, { useState } from 'react'; |
A Counter component that contains a count
state. The initial value of count is 0.
1 | function Counter() { |
You read the state uing JSX syntax
1 | <p>You clicked {count} times</p> |
You update the state using the returned setter
1 | setCount(count + 1) |
Updating state based on the previous state
If we change the code to call setCount multiple times, it does not work because set function doesn’t change the state variable in the already running code.
1 | function handleClick() { |
We need to pass an updater function to the set function instead.
1 | function handleClick() { |
React puts your updater functions in a queue. Then, during the next render, it will call them in the same orde