React: Using State Within An Arrow Function Component
- Published on
- -1 min read
When building React applications, my components would consist of a mixture of React Function and Class components. As much as I love to use React Function components due to their simple, lightweight and concise code construction, I had a misconception they were limited in features.
React Function components are generally classed as "stateless" where I would go as far as to send props (if required) and return the rendered output in HTML. So whenever there was a need for some form of interaction where state was required, a Class component would be used.
It was only until recently I was made aware of React Hooks that allowed React Function components to have state. Let's take a look at a simple example where we are increasing and decreasing a number.
import React, { useState } from 'react';
const CounterApp = () => {
const [state, setState] = useState({
count: 0
});
const incrementCount = () => {
setState({
count: state.count + 1,
});
}
const decrementCount = () => {
setState({
count: state.count - 1,
});
}
return (
<div>
<h1>{state.count}</h1>
<button onClick={incrementCount}>Increment</button>
<button onClick={decrementCount}>Decrement</button>
</div>
);
};
export default CounterApp;
In the code above we have accomplished two things:
- Storing our counter in state.
- Click handlers
The useState()
hook declaration accepts properties in the way we are accustomed to when used in a Class component. The similarity doesn't stop there, you'll also notice the same approach when setting and getting a state property.
Multiple states can also be declared and through the array destructuring syntax lets us give different names to the state variables we declared by calling useState
. Really cool!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
Even though this post has concentrated on state, I've found React Function components offer similar features as a Class component. This is how I will be building my components going forward.
Before you go...
If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!
Leave A Comment
If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.