React Hooks π
Letβs dive in and get a better understanding about react hooks
Table of contents
No headings in the article.
What are Hooks?π€
Hooks are specially-implemented functions that let us add functionality to React components beyond just creating and returning React elements.
Weβll look at some of the react hooks in this article π§
useState - Persist state within a component function
useReducer - Similar to useState, but for a state that involves multiple sub-values
useEffect - Perform side effects within our component functions
Letβs start with useState hook π
The useState hook lets us "remember" a value within a component function. Since our component function may be called many times throughout the lifecycle of the component, any variable we declare normally (i.e. with let myVar = ...) will get reset. With useState, React can remember a state variable for us, making sure it gets passed into our component instance correctly.
The useState hook takes a single argument, our initial state, and returns an array containing two elements:
state - the current state
setState - a function to update our state
E.g. const [state, setState] = useState(initialValue)
The useState hook can store any type of value: a number, a string, an array, an object, etc.
Example
Awesome! We start with an initial state of 0 and when we click on the button we see the count value will increase by 1.
Easy right??π
Yeah, itβs super easy and a really important react hook. I hope it will help you see you in the next article with other react hooks.
Thank you π