Understanding React Hooks; useState()

Understanding React Hooks; useState()

If you probably just started learning React or you are coming from a different framework entirely to learn React, there are some concepts in React that are bound to confuse you. React is an amazing library and there are some of the features React has and uses that are actually tied to JavaScript and without a solid understanding of JavaScript, it is really hard to grasp.

This is the first article in the 'React Hooks' series where I will demystify Hooks - one of the key concepts every React developer should know.

In this article, I will help you understand the useState React Hook, and how to use it.

Prerequisites

This article assumes you have the following:

  • Node >= 8.10 installed on their local development machine npx 5.2 or higher installed on their local development machine
  • Basic understanding of JavaScript's ES6.
  • Basic knowledge of ReactJS

What are Hooks in ReactJS?

Hooks are a set functions that let you "hook into" React state and lifecycle hooks from function components.

In React, you can declare and use components using either the Class-based or Functional components. Hooks are supported in Class components because Hooks were introduced for Functional components which is the latest way we can declare components in React, so this article will be mainly focused on how to use Hooks on that which it is made for: Functional components

That is what Hook really means, it just provides some functions we use to work with function components so we can use some features of React and those features will be explained further in this article. There are also different types of hooks and each has its own use cases.

  • useState Hook
  • useEffect Hook
  • useContext Hook
  • useReducer Hook
  • useRef Hook
  • useCallback
  • useMemo
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

Rules of Hooks

Before I dive into explaining the first Hook on the list above, I will like to state and explain the rules of hooks - where you can use hooks and where you cannot use them.

  • Only call at the top level of your component: Don’t call Hooks inside loops, conditions, or nested functions. Hooks are functions, so before we use them we need to call them but there are places in your code you shouldn't do it. The code below explains where we can use a React hook and where we should not use them.

const hooksRule = () =>{
// You should call your hook function here and declare it here
const [testing, setTesting] = useState()

function hello(){
// Don't call Hooks in nested function in your components
}

for(let i = 0; i<=10; i++){
// Don't call Hooks in loops
}


return <h1> Rules of Hooks </h1>

}

export default hooksRule
  • Only call Hooks from React function components: Don’t call Hooks from regular JavaScript functions. Hooks are functions but it is also a React feature and should strictly be used and called in a React function components. See the code example below

const notAReactComponent = () =>{
// You should not call your hook function here

const [testing, setTesting] = useState() 

// This is wrong and would not work

}

const hooksRule = () =>{
// You should call your hook function here and declare it here 
// within your React Function Components
const [testing, setTesting] = useState()


return <h1> Rules of Hooks </h1>

}

export default hooksRule

Those are the rules of hooks when calling them, luckily React even provides a (ES Lint)linter plugin to check and alert you when you break these rules.

The useState React Hook

State Hooks used as "useState" in React is a hook that is used to store local state in React after every render of a function component. You call this hook and set a state to it and it returns an array of two things; first, the current state value and a function to update the value.

In JavaScript, when functions are called they create an execution context where the code is executed. After that, the function is destroyed and all it's state is lost except the data returned using the return keyword in JavaScript.

The same concept applies here with React as its features as I stated from the beginning are strongly tied to JavaScript.

State in React is a posh word for data/value used in an application, this could be a value in variable or information gotten from forms e.t.c

A React function component when executed and re-rendered would lose states that are present, to solve this, React has a feature called State Hooks that gives us the ability to store and preserve these states across React even after many re-render and execution.

How to use State Hooks

The "useState" Hook being a function accepts only one argument and that is the initial value of the state, the initial value can be any data type; numbers, strings, arrays, or object depending on what you are building and why you need it, and the useState hook returns an array of the current state value and a function to update it which can be called in an event listener or anywhere else within the function component.

Below is an example of useState in action, the example is a counter that increments every time a button is clicked.

const updateCounter = () =>{
// Call the useState hooks
const [counter, setCounter] = useState(0)

return <div>
 <p>Number of times the button was clicked: {counter} </p>
<button onClick={ ()=> setCounter(counter + 1)}> 
Click me to increase counter 
</button>

</div>
}

in the code snippet above, when the button is clicked, the setCounter function is called and the new state value is passed and the counter state is updated which also reflect in the p tag.

Array Destructuring

You may probably noticed how the useState was used above and how the value was stored using the square bracket syntax. The syntax has nothing to do with React but JavaScript, the syntax is called array destructuring, which is a way we set each value of an array into a variable.

As explained earlier, the useState hook returns an array of two things, the current state and a function to update it, and we need to store these returned values in a variable to be able to use them, hence we destructure the returned array and store each value in a separate variable, hence the syntax.

const [counter, setCounter] = useState(0)

To get more context on array destructing, you can read this article here.

That is all about the State hooks and how it is used with the JavaScript features it utilizes. We use it to store states in React so we can access them after each re-render without losing the value of that state.

Conclusion

We are at the very end of this article, I really do hope you enjoyed the article.

The next article on this React Hook series would be on the Effect Hook and how it can be used, so follow me to get notified when it gets posted.

If you did learn something please like, share, comment, just do anything to make it go viral.

If you have any questions concerning Go, Javascript, TailwindCSS, Open-source, or this article? You can reach me on Twitter. Till next time, see ya. Thank you.