What Are React Hooks

Jake Peterson
2 min readApr 25, 2021

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.

useEffect: Similar to componentDidMount, componentDidUpdate, and componentWillUnmount, except all in one. React will run these effects after the component is rendered.

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.

Don’t call hooks in javascript functions only call them in functional components or custom hooks.

Always call hooks at the top of your functional component, never inside nested functions, loops, or conditions. This will make sure your hooks are called the same way every time the component renders.

In a future blog I would like to cover the syntax of these hooks and how to actually apply them in your code… as well as how to build your own hooks.

Sources:

--

--