Hooks are used inside function components and will not work inside class components. Hooks are used to replace setState and life cycle methods that class components use in function components.

State Hook

In react each components has their own individual state that is unrelated to other components. Hooks equivalent of that is useState.

Code taken from

To us useState you need to first import it. On line 4 you can see an example of useState. To break it down useState returns an array which we deconstruct on the left side. The count is the where the value is stored and setCount is the method or function used to change the value. This is not only limited to primitive data types, it can be used for arrays and objects as well.

Effect Hook

In react class components have life cycle methods like componentDidMount, componentDidUpdate and componentWillUnmount, hooks equivalent of that is useEffect which combines all three lifecycle.

Code taken from

In the above example you can see the 3 different lifecycle methods being used. Using hooks the equivalent would be the bottom code.

Code taken from

By default useEffect is always called on the first render and after every update. Inside useEffect the subscribeToFriendStatus method is called so it is the equivalent of componentDidUpdate as well as componentDidMount. The return method in useEffect is for clean up which is the equivalent of componentWillUnmount which will run when the component will unmount.

Use effect can also be used more than once in a component, react will run every useEffect so you can have multiple useEffect inside a component. Use effect can also take in a array parameter.

Code taken from

When you pass an empty array as a second parameter it means that useEffect does not depend on any values from prop or states so it will only be run once. In the above example doSomething is called but it uses someProp, the right way would be to add someProp into the array.

Code taken from

Any values from state and props used inside the useEffect should be included in the array.


Hooks allows you to use state and lifecycles without having to use a class. While this means that using hooks will make it faster it does not mean you have to use it.

Written by


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store