
With the invent of the functional components in ReactJS, we can perform state management using a famous hook called useState
. We declare and track the component's state using this hook. It takes an optional argument as the initial state value and returns the current state and a function to update it.
const [counter, setCounter] = useState(1);
In the above code snippet, we initialize the counter
state with the value of 1
, and the variable counter
will always give us the current state value. If we want to update the state, we do not directly update the counter
variable. Instead, we will explicitly call the setCounter()
method and update the state value.
const incrBy3() => {setCounter(counter + 3);}
The method incrBy3()
update the current state by incrementing the counter value by 3
. The update of a state triggers the re-rendering of your component. It means the useState
hook gets called internally to provide you with the updated counter
value that you may use in your JSX.
<div className="counter-box">
<span>{ counter }</span>
<button onClick={incrBy3}>+ 3</button>
</div>
The above snippet shows the JSX code that renders the current state value(counter
) and a button click-event that uses the updater function(setCounter()
) to change the state.
If we put everything together in a ReactJS component, it will look like this,
import React, { useState } from 'react'; export default function App() { const [counter, setCounter] = useState(1); const incrBy3 = () => { setCounter(counter + 3); }; return ( <div className="container"> <h1>Increment By 3</h1> <div className="counter-box"> <span>{ counter }</span> <button onClick={incrBy3}>+ 3</button> </div> </div> ); }
To conclude, ReactJS's standard hooks got lots to offer when you use functional components. The useState
hook helps us create and track the state changes. Knowing the extra bit of information about the lazy initialization
and previous state
value may help us deal with situations.