Try the new React documentation.
These new documentation pages teach modern React and include live examples:
- State: A Component’s Memory
- useState
The new docs will soon replace this site, which will be archived. Provide feedback.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
The introduction page used this example to get familiar with Hooks:
import React, { useState } from 'react';function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> );}
We’ll start learning about Hooks by comparing this code to an equivalent class example.
Equivalent Class Example
If you used classes in React before, this code should look familiar:
class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); }}
The state starts as { count: 0 }
, and we increment state.count
when the user clicks a button by calling this.setState()
. We’ll use snippets from this class throughout the page.
Note
You might be wondering why we’re using a counter here instead of a more realistic example. This is to help us focus on the API while we’re still making our first steps with Hooks.
Hooks and Function Components
As a reminder, function components in React look like this:
const Example = (props) => { // You can use Hooks here! return <div />;}
or this:
function Example(props) { // You can use Hooks here! return <div />;}
You might have previously known these as “stateless components”. We’re now introducing the ability to use React state from these, so we prefer the name “function components”.
Hooks don’t work inside classes. But you can use them instead of writing classes.
What’s a Hook?
Our new example starts by importing the useState
Hook from React:
import React, { useState } from 'react';function Example() { // ...}
What is a Hook? A Hook is a special function that lets you “hook into” React features. For example, useState
is a Hook that lets you add React state to function components. We’ll learn other Hooks later.
When would I use a Hook? 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. We’re going to do that right now!
Note:
There are some special rules about where you can and can’t use Hooks within a component. We’ll learn them in Rules of Hooks.
Declaring a State Variable
In a class, we initialize the count
state to 0
by setting this.state
to { count: 0 }
in the constructor:
class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; }
In a function component, we have no this
, so we can’t assign or read this.state
. Instead, we call the useState
Hook directly inside our component:
import React, { useState } from 'react';function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
What does calling useState
do? It declares a “state variable”. Our variable is called count
but we could call it anything else, like banana
. This is a way to “preserve” some values between the function calls — 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. In our example, we just want a number for how many times the user clicked, so pass 0
as initial state for our variable. (If we wanted to store two different values in state, we would call useState()
twice.)
What does useState
return? It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState()
. This is similar to this.state.count
and this.setState
in a class, except you get them in a pair. If you’re not familiar with the syntax we used, we’ll come back to it at the bottom of this page.
Now that we know what the useState
Hook does, our example should make more sense:
import React, { useState } from 'react';function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
We declare a state variable called count
, and set it to 0
. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count
, we can call setCount
.
Note
You might be wondering: why is
useState
not namedcreateState
instead?“Create” wouldn’t be quite accurate because the state is only created the first time our component renders. During the next renders,
useState
gives us the current state. Otherwise it wouldn’t be “state” at all! There’s also a reason why Hook names always start withuse
. We’ll learn why later in the Rules of Hooks.
Reading State
When we want to display the current count in a class, we read this.state.count
:
<p>You clicked {this.state.count} times</p>
In a function, we can use count
directly:
<p>You clicked {count} times</p>
Updating State
In a class, we need to call this.setState()
to update the count
state:
<button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button>
In a function, we already have setCount
and count
as variables so we don’t need this
:
<button onClick={() => setCount(count + 1)}> Click me </button>
Recap
Let’s now recap what we learned line by line and check our understanding.
1: import React, { useState } from 'react'; 2: 3: function Example() { 4: const [count, setCount] = useState(0); 5: 6: return ( 7: <div> 8: <p>You clicked {count} times</p> 9: <button onClick={() => setCount(count + 1)}>10: Click me11: </button>12: </div>13: );14: }
- Line 1: We import the
useState
Hook from React. It lets us keep local state in a function component. - Line 4: Inside the
Example
component, we declare a new state variable by calling theuseState
Hook. It returns a pair of values, to which we give names. We’re calling our variablecount
because it holds the number of button clicks. We initialize it to zero by passing0
as the onlyuseState
argument. The second returned item is itself a function. It lets us update thecount
so we’ll name itsetCount
. - Line 9: When the user clicks, we call
setCount
with a new value. React will then re-render theExample
component, passing the newcount
value to it.
This might seem like a lot to take in at first. Don’t rush it! If you’re lost in the explanation, look at the code above again and try to read it from top to bottom. We promise that once you try to “forget” how state works in classes, and look at this code with fresh eyes, it will make sense.
Tip: What Do Square Brackets Mean?
You might have noticed the square brackets when we declare a state variable:
const [count, setCount] = useState(0);
The names on the left aren’t a part of the React API. You can name your own state variables:
const [fruit, setFruit] = useState('banana');
This JavaScript syntax is called “array destructuring”. It means that we’re making two new variables fruit
and setFruit
, where fruit
is set to the first value returned by useState
, and setFruit
is the second. It is equivalent to this code:
var fruitStateVariable = useState('banana'); // Returns a pair var fruit = fruitStateVariable[0]; // First item in a pair var setFruit = fruitStateVariable[1]; // Second item in a pair
When we declare a state variable with useState
, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using [0]
and [1]
to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.
Note
You might be curious how React knows which component
useState
corresponds to since we’re not passing anything likethis
back to React. We’ll answer this question and many others in the FAQ section.
Tip: Using Multiple State Variables
Declaring state variables as a pair of [something, setSomething]
is also handy because it lets us give different names to different state variables if we want to use more than one:
function ExampleWithManyStates() { // Declare multiple state variables! const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
In the above component, we have age
, fruit
, and todos
as local variables, and we can update them individually:
function handleOrangeClick() { // Similar to this.setState({ fruit: 'orange' }) setFruit('orange'); }
You don’t have to use many state variables. State variables can hold objects and arrays just fine, so you can still group related data together. However, unlike this.setState
in a class, updating a state variable always replaces it instead of merging it.
We provide more recommendations on splitting independent state variables in the FAQ.
Next Steps
On this page we’ve learned about one of the Hooks provided by React, called useState
. We’re also sometimes going to refer to it as the “State Hook”. It lets us add local state to React function components — which we did for the first time ever!
We also learned a little bit more about what Hooks are. Hooks are functions that let you “hook into” React features from function components. Their names always start with use
, and there are more Hooks we haven’t seen yet.
Now let’s continue by learning the next Hook: useEffect. It lets you perform side effects in components, and is similar to lifecycle methods in classes.
FAQs
What is use state hook React? ›
The useState hook is a special function that takes the initial state as an argument and returns an array of two entries. UseState encapsulate only singular value from the state, for multiple state need to have useState calls.
How do you use React hooks effectively? ›- Use Hooks as They're Supposed to Be Used. ...
- There's an ESLint Plug-In for React Hooks — Use It. ...
- useState Can Be Used With Objects Too! ...
- Custom Hooks Are Awesome! ...
- Don't Use Prop Drilling. ...
- Conclusion.
useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.
How to set value using useState? ›If you want to set an initial value for the variable, pass the initial value as an argument to the useState function. When React first runs your component, useState will return the two-element array as usual but will assign the initial value to the first element of the array, as shown in figure 5.
Why do we use useState hook? ›The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these! We could create multiple state Hooks to track individual values.
Should I use useState or useEffect? ›The useState hook is used for storing variables that are part of your application's state and will change as the user interacts with your website. The useEffect hook allows components to react to lifecycle events such as mounting to the DOM, re-rendering, and unmounting.
What is the best practice to use function in useState hook? ›Always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
Are React Hooks difficult? ›React hooks are a constant source of difficult to write and non-deterministic tests. Class components also suffer from the same problems. Now after learning about it I'll never go back to class components. Those aren't the only two options.
Is it better to use React Hooks or classes? ›Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes.
Why we use useState instead of variable? ›Use a state variable when a component needs to “remember” some information between renders. State variables are declared by calling the useState Hook. Hooks are special functions that start with use. They let you “hook into” React features like state.
Should I use Redux or useState? ›
You should use local state i.e. useState as much as possible. Redux state should be the last resort. Only use Redux state if you absolutely need to pass data from one end of the application all the way to another end. This is both good practice for tight coupling and good performance.
What can I use instead of useState? ›An alternative to the useState Hook, useReducer helps you manage complex state logic in React applications.
How do you call a function in useState hook? ›To use callback in the useState hook, we need to use the useEffect hook that triggers after state update and call the function after that. We need to pass state in the useEffect Dependency Array. useEffect is triggered when the state updates and then calls the inside function immediately.
How do you pass a component in useState? ›You can store components and even functions in useState, simply wrap it with an arrow function.
What is the output of useState () hook? ›useState() hook allows one to declare a state variable inside a function. It should be noted that one use of useState() can only be used to declare one state variable. Example: Program to demonstrate the basic use of useState() hook.
Does useState cause a rerender? ›As we already saw before, React re-renders a component when you call the setState function to change the state (or the provided function from the useState hook in function components). As a result, the child components only update when the parent component's state changes with one of those functions.
Can useState hold an object? ›One of React's most commonly used Hooks is useState , which manages states in React projects as well as objects' states. With an object, however, we can't update it directly or the component won't rerender.
Does useState hook cause Rerender? ›useState() Hook is widely used in React applications to re-render the components on state changes. However, there are scenarios where we need to track state changes without re-rendering the components. But, if we use the useRef() Hook, we can track the state changes without causing component re-renderings.
When should you avoid useEffect? ›- You don't need Effects to transform data for rendering. For example, let's say you want to filter a list before displaying it. ...
- You don't need Effects to handle user events.
By default, useEffect always runs after render has run. This means if you don't include a dependency array when using useEffect to fetch data, and use useState to display it, you will always trigger another render after useEffect runs. Unless you provide useEffect a dependency array.
Does useEffect run before useState? ›
This useEffect will run only once when the button is clicked. The variable will change from the useState, and will cause the useEffect to run. A couple of things to note about the useEffect are that; the first time it will run is when the component that's using it is mounted.
Does useState hook update immediately? ›React do not update immediately, although it seems immediate at first glance. React keep track of the states by queuing them in the order they are called. React queue all the changes to be made and update once the component Re-render which is not immediate.
What are the rules you must follow while using Hooks? ›There are 3 rules for hooks: Hooks can only be called inside React function components. Hooks can only be called at the top level of a component. Hooks cannot be conditional.
How do you master React Hooks? ›When using React Hooks there are a few rules to adhere to: Only call hooks at the top level of a component: You shouldn't use Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any return keyword.
What is the drawback of React hooks? ›Wrapper hell (caused by design patterns: HOC, render prop, drilling prop) Huge components (that hard to test and maintain, hard to co-locate code) Confusing classes (this keyword, hard to make it reusable)
Why i don't use React hooks? ›The problem. If you create a React component using hooks you are forced to write code in a way that makes it difficult to manage. Look at this code: If you don't know anything about React this may look a little odd to you.
Is React overkill for small apps? ›Using React can be overkill if the requirements are too simplistic. For example, you need to make a few pages with no dynamic elements or customization. In cases like these, it might suffice to use simple HTML and a bit of JavaScript.
Why Hooks instead of lifecycle methods? ›These lifecycle methods are of course not applicable to functional components because they can only be written/contained within a class. However, React hooks give functional components the ability to use states. Hooks have gaining popularity because they make working with React cleaner and often less verbose.
Why use Hooks instead of Redux? ›Redux vs Hooks & Context API
Hooks let you use state and other React features without writing a class, which brings a positive impact on the performance and the readability of the code. Since Hooks are regular JavaScript functions, you can combine built-in Hooks provided by React with your own “custom Hooks”.
Although Redux isn't always necessary, replacing it with a tool kit that was not made for the same purpose will not suffice. React Hooks are great but they do not replace Redux and they never will. In this post, we'll dive into how to determine when to use Redux, React Hooks, or both.
What is the use of use effect hook? ›
The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional.
Why should I use React hook form? ›With react hook forms vs formik, you can isolate a component and avoid having other components re-render. Using this feature, other child components won't be rendered in an unwanted manner which will improve performance.
What is useForm hook in React? ›useForm is a custom hook for managing forms with ease. It takes one object as optional argument. The following example demonstrates all of its properties along with their default values. function App() { const methods = useForm(); return null; }
Why use React Hooks instead of classes? ›It is famous for its ease of use and its readability, allowing companies and startups to adopt it. But classes can be unwieldy and hard to understand. Hooks allow you to use state, lifecycle methods, and other functionalities of React without using classes.
What does useEffect () hook do in React? ›What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates.
Can I call Hooks in useEffect? ›To avoid confusion, it's not supported to call Hooks in other cases: 🔴 Do not call Hooks in class components. 🔴 Do not call in event handlers. 🔴 Do not call Hooks inside functions passed to useMemo , useReducer , or useEffect .
How does useEffect () hook gets executed? ›In the code above, we used the useEffect hook. It takes a function as input, which is executed after the initial rendering, as well as re-rendering, of the component. After each rendering, one the DOM has been updated and the function passed to useEffect is invoked.
Are React Hooks still used? ›React hooks have been around for some time now, yet many React developers are not actively using them.
What is most used React hook? ›One of the commonest use cases of the useEffect hook is fetching and prefetching data from an API. To illustrate this, we'll use fake user data I created from JSONPlaceholder to fetch data with the useEffect hook. In the code above, we created a users state using the useState hook.