
Introducing Hooks
Hooks in React JS are a new addition in Version 16.8. They let you use state and other React features without writing a class.
Example:
import React, { useState } from 'react' function HookEx1() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ) } export default HookEx1
This new function useState is the first “Hook” . When you click the button, it increments the value.
useState is a Hook. We call it inside a function component to add some local state to it. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together.
Equivalent Class Example
If you used classes in React before, this code should look familiar:
class HookEx1 extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); } }
What’s a Hooks in React JS ?
Our new example starts by importing the useState Hook from React:
import React, { useState } from 'react'; function Example() { // ... }
What is a Hook? A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components. We’ll learn other Hooks later.
When would I use a Hook? If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We’re going to do that right now!