In this lesson, we discuss the motivation behind React Hooks and see a few examples of how React Hooks can help share logic between our React components.
📝 This lesson's quiz can be found - here. 🗒️ Solutions for this lesson's quiz can be found - here. 📖 This lesson's lecture slides can be found - here. 🎥 React Today and Tomorrow | React Conf 2018 - link. 📖 React Hooks API Reference | React Docs - link. 📖 React Rules of Hooks | React Docs - link.
In our React Introduction lesson, we mentioned how components in React can be created with either a class or a function. Traditionally, React required us to create components with classes to:
statewithin a component.
Be able to use other certain React features (e.g lifecycle methods).
As a result, class components were often used as "container" components since these components were stateful and responsible in defining and providing data to other components. Function components didn't keep their own state and were more used as "presentational" components to determine the presentation of UI.
From this, a popular pattern emerged for having components be divided into two categories - "container" and "presentational". There were variations to this approach but as of late, Dan Abramov (React core team member) does not suggest splitting components with the container and presentational pattern anymore. This is in large part due to the presence of a new React feature - React Hooks.
When it comes to sharing stateful logic between any components, other more advanced patterns emerged such as:
Higher Order Components - Functions that take a component and return a new component with additional data or functionality
Render Props - Props whose value is a function where the component calls the prop function to return the React element instead of implementing its own logic.
Higher-order components and render props are advanced patterns that simply emerged within the React community to handle component logic re-use. Though both these patterns help abstract shared logic, they tend to make components difficult to understand.
Dan Abramov summarized the above issues as symptoms of a certain particular problem. Roughly quoted, this is because React didn't provide a simpler/smaller primitive to adding state or lifecycle than a class component. Class components are difficult to split up unless more complicated patterns are used which then can lead to something often labeled as "wrapper hell" where component declarations are wrapped over one another multiple levels deep.
Motivation behind React Hooks#
This is where Hooks come in. Hooks aims to solve the difficulties of logic reuse by enabling us to write functional components that have access to features like
context, lifecycle methods,
ref, etc. without having to write a Class component.