Until about a year ago the only way to use state in React was in a class component. As you most likely know state is where we can store valuable data about the component. This can be extremely useful because state is also dynamic and can be constantly updated. Thankfully React released version 16.8 which came with hooks. Hooks allow us to access state and other react features all in functional components.

The Need For Hooks

React has higher order components which means the data in the state of a parent component is only passed down, and even at that you still have to render props in the child component to display this information. You also have to wrap your components correctly to make sure the data is flowing correctly, you get the point… it can be a bit of a hassle sometimes. With hooks, you can share the logic stored in state with other components without having to worry about component hierarchy. You also can split the component and its logic into more manageable functional components and you get rid of “this” which is a can of worms for another blog.

Examples of Hooks

useState: Similar to this.setState, a function which creates a local state that is preserved even through re-renders.

Rules of Hooks

As you can see hooks can be extremely useful and save a lot of time but they also have some rules you must follow.