Hooks in React

What is a Hook in React?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. React provides us with built-in hooks. For example, useState is a function that lets you use state in functional components.

When would using hooks be useful?

If you are writing a functional component and need to add state to it, instead of converting the component into a class component you can use Hook inside the functional component.

The useState Hook

The useState hook is the most used hook in the framework. useState declares our state variable. It is the same way to use capabilities that this.state provides in a class.

The only argument to the useState() hook is the initial state. useState returns a pair of values, which are the current state and the setter, which is a function that updates the state.

The useEffect Hook

The useEffect Hook lets you perform effects into functional components. Fetching data and changing the DOM in React are examples of side effects. By using this hook, we tell React that our component needs to do something after render. React will remember the effect passed down and call it after performing the DOM updates. useEffect is called inside of the component and lets us access the state variable right from the effect.

Conclusion

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. They are very useful, they allow you to reuse stateful logic without changing component structure.

--

--

--

Fullstack software engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

String Reversal JavaScript

Using JavaScript to Work with Spreadsheets, Part 4: Making the CLI More Robust

Building Small Form-Based JS Apps: Step-by-step with ES6

WhatsApp Web — Editing everyone’s deleted messages for fun

Build your chrome extension

Power your Cypress tests with CircleCI

A Guide to Understanding the ‘this’ Keyword in React Components

Mendix — How to build a video link from Youtube

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cori b

Cori b

Fullstack software engineer

More from Medium

React Hooks & ‘customHook(s)’

React Redux overview

REACT (PART-2)…