Introduction to React hooks

Learn how Hooks can help you build React applications

Hooks is a feature that will be introduced in React 16.7, which will change the way we write React applications in the future.

Before the emergence of Hooks, certain key things in components could only be achieved using class components: owning their own state and using life cycle events. Functional components are lighter and more flexible, but their functions are limited.

Hooks allow functional components to have state and respond to life cycle eventsThe same is true and makes the class components obsolete. They also allow functional components to have good ways of handling events.

Access status

useuseState()API, you can create a new state variable and have a way to change it.useState()Accepts the initial value of the state item and returns an array containing state variables and the function you use to change the state. Since it returns an array, we useArray deconstructionVisit each individual project as follows:const [count, setCount] = useState(0)

This is a practical example:

import { useState } from 'react'

const Counter = () => { const [count, setCount] = useState(0)

return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ) }

ReactDOM.render(<Counter />, document.getElementById(‘app’))

You can add as manyuseState()Make the required calls to create the required number of state variables. Just make sure you are at the top level of the component (not at theifOr in any other block).

Example on Codepen:

Look at the penReact Hooks example #1 counterBy Flavio Copes (@flaviocopes) InCipher pen.

Tech Wiki Online!