Getting Started with React Hooks

React Hooks are a great new feature coming in React 16.7. React 16.6 brought some awesome new things like React.memo() and React.lazy and Suspense. The React team isn't stopping there.

Hooks are a feature that you'll end up using every single day of your React development. You can give them a try in React 16.7.0-alpha right now and are being discussed in an open RFC. Hooks are great because we get more tools as React developers.

If you want to use state or lifecycle methods you would normally have to change to using React.Component and classes. Hooks let us use these features in functional components!

The React Hooks intro gives a good section on this: Classes confuse both people and machines. The gist is classes can sometimes be confusing and can be written any number of ways. Dive into somebody else's project and you could be in for a world of different syntax and style choices.

There are no plans to remove classes support. We just have another way to code

By allowing classes to be converted into smaller functional components, we can even further break out parts of our application into smaller and more focused components.

The State Hook allows us to use state in React functional components. This gets us a step closer to using functional components over class components. The next part of moving to functional components is lifecycle methods.

Effects are similar to componentDidMount, componentDidUpdate, and componentWillUnmount

This is what the Effect Hook is for. Side-effects are things you want your application to make like:

Since useEffect() runs every time a component renders, how do we get it to only run once, on mount? The Effect Hook can take a second argument, an array. It will look through the array and only run the effect if one of those values has changed.

componentDidMount: Runs once

// only run on mount. pass an empty arrayuseEffect(()=>{// only runs once},[]);

componentDidUpdate: Runs on changes

// only run if count changesuseEffect(()=>{// run here if count changes},[count]);

React State and Effect Hooks are wonderful additions to the library and will be tools to make it easier to learn React for new developers. A lot of Vue's success is in its simplicity in creating components. It's just an object.

Now with React, you don't have to differentiate between "is it a class?" or "should I use a functional component?"