React Hooks are currently available in the alpha release of
[email protected]
.
In this article, we will attempt to understand what is React Hooks and rules we have to follow when using them. Plus we will create a counter application using useState React Hook.
React Hooks are functions that let us hook into the React state and lifecycle features from function components.
By this, we mean that hooks allow us to easily manipulate the state of our functional component without needing to convert them into class components.
Hooks don’t work inside classes(because they let you use React without classes). By using them, we can totally avoid using lifecycle methods, such as componentDidMount, componentDidUpdate, componentWillUnmount. Instead, we will use built-in hooks likeuseEffect
.
Basic Built-in Hooks :
React.createContext
) and returns the current context value, as given by the nearest context provider for the given context — useContextHooks are JavaScript functions, but they impose two additional rules:
Let’s dive in and see how useState hook feature works.
To start, create a new React app called counter
using create-react-app.
$ npx create-react-app counter$ cd counter$ npm start
Since React Hooks are currently available in the alpha release we have to install react and react-dom again.
$ npm install -s react@16.7.0-alpha.0 [email protected]
counter app
Now we need to create Counter
component and a button to update the counter. And set an initial state (count) within Counter
to the value of 0. And add an event handler so that whenever the button is clicked, the count
is increased by 1.
We call the useState
Hook directly inside our component:
const [count, setCount] = useState(0);
declares a state variable. The only argument to the useState()
Hook is the initial state.
useState 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.
You can use the State Hook more than once in a single component:
function ExampleWithManyStates() { const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);}
const [count, setCount] = useState(0);
The array destructuring syntax lets us give different names to the state variables we declared by callinguseState
. These names aren’t a part of theuseState
API.
Here you can find a working example for React Hook useState: https://github.com/jscodelover/react-hooks
Follow me on Twitter, LinkedIn or GitHub.
I hope this article is useful to you. Thanks for reading & Keep Coding !!