Skip to content

Instantly share code, notes, and snippets.

@reedsa
Created April 26, 2019 15:10
Show Gist options
  • Save reedsa/c4e03d452b2c896ed58dc03e8c69c5f8 to your computer and use it in GitHub Desktop.
Save reedsa/c4e03d452b2c896ed58dc03e8c69c5f8 to your computer and use it in GitHub Desktop.

React Hooks

Hooks in React enable usage of React state and lifecycle features without using a class. Released in React v16.8.0, Hooks resolve issues like sharing stateful logic across components.

Rather than writing higher-order components, a customized hook can be implemented outside of a component in order to reuse that logic and test it in isolation. This also means the components themselves become simpler to manage by breaking it into smaller pieces of state related functions.

Functional components have many benefits over using classes. The top-down approach in functional components means it's easier to read and comprehend. In a class, binding this can be difficult to keep track of and introduces potential for bugs. In addition, without classes there is no need to wire up the component lifecycle functions and write potentially complicated logic to identify changes in props or state.

Building a State Hook with useState

The useState hook will add local state to a functional component. This function returns an array pair, one being a variable for the current state value and another for a function to update the state value.

For more information about the State Hook, check out the React Docs.

Producing Side Effects using the Effect Hook with useEffect

In a class, the lifecycle functions of componentDidMount, componentDidUpdate and componentWillUnmount can help fetch data or manipulate the DOM. Without the ability to do this inside a functional component React forced using a class to take advantage of these features. With the useEffect hook, these features can be mimicked without the need for a class component.

React will run the provided callback function after the DOM has updated on every render.

For more info, see the React Docs

Additional Resources

In addition to the blog post, Dan Abramov had a great talk about React Hooks at React Conf 2018.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment