Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class which are often difficult to use and understand . Below are the different react hooks .
Basic Hooks
- useState
- useEffect
- useContext
- Additional Hooks
- useReducer
- useMemo
- useCallback
- useRef
- useLayoutEffect
- useImperativeHandle
- useDebugValue
We will be discussing about every hooks in the future but for this article we will be discussing useState hook. It is one of the most important react hooks .
By using useState, whenever value of the state changes the component gets re rendered automatically . First, let us see the scenario where useState is necessary .
Let's say we want to create a button and on every click of the button we want to increase the value of counter by one . For this example, we will be using App.js file only .
import './App.css';
function App() {
let counter = 0;
//increase the counter by one
const handleIncreaseCounter = () => {
counter = counter+1;
console.log(counter);
};
return (
<div>
<h1>Learn about useState!</h1>
<h2>{counter}</h2>
<button onClick={handleIncreaseCounter}>
Increase counter
</button>
</div>
);
}
export default App;
The example above doesn't update the DOM, instead it only increases the value of counter on every click on console but not on the browser. So, we need useState hook to update the DOM when any state changes.
To use the useState Hook, we first need to import it into our component. At the top of your component, import the useState Hook.
import { useState } from "react";
Its a good practice to keep the useState import always on the top . Whenever, we define useState, it returns 2 values.
- the current state
- the function where you can update the state.
import { useState } from "react";
function App() {
const [counter, setCounter] = useState(1);
}
Now, in order to update the state we will be using a button say Increase counter
function App() {
const [counter, setCounter] = useState(1);
return (
<div>
<h2>Value: {counter}</h2>
<button onClick={handleIncreaseCounter}>
Increase counter
</button>
</div>
);
}
After that, let us create a function to increase the counter by one
//increase the counter by one
const handleIncreaseCounter = () => {
setCounter(counter+1);
};
Then, on clicking the button we can see the value of counter gets updated in the DOM as useState re renders the component whenever the value of state changes .
So, the final App.js file will look like this:
import { useState } from "react";
function App() {
const [counter, setCounter] = useState(1);
//increase the counter by one
const handleIncreaseCounter = () => {
setCounter(counter+1);
};
return (
<div>
<h2>Value: {counter}</h2>
<button onClick={handleIncreaseCounter}>
Increase counter
</button>
</div>
);
}
export default App;
That was about useState hook in React. The next blog post will be about useEffect hook . Thanks for reading .
Happy Coding !