React Hooks at a glance

Hooks mainly used to provide state, lifecycle methods and all other features in functional component that we generally get in a class component. But also makes it easier to apply.

Where to use

Hooks are mainly used in react functional components. Because functional components are stateless and hooks provide us facility to use most of the react features in them.

Why we prefer hooks

To understand this we should first understand why we use functional component because ultimately they are used inside functional components.

benefits of using functional component

  • It avoids unnecessary use of inheritance that we generally use in class component.
  • hence no need to declare constructor or call super.
  • No need to bind functions to component’s this context.

Functional components are higher in demand and as they are stateless in nature we need some mechanism to use state and lifecycle methods in them, thus hooks came into picture. Let’s see some of the examples-

useState

Mainly used to create state variable and also provide a function to modify the state. It can be used any number of times.

const [ name, setName ] = useState ( “Rajiv”)

useEffect

This hook can be used for 3 lifecycles- componentDidMount, componentDidUpdate and componentWillUnmount. It can be used multiple times in a component.

useEffect ( ()=>{console.log(‘this will work as componentDidMount’);}, [ ])

useEffect ( ()=>{console.log(‘this will work as componentDidUpdate’);}, [ name])

useEffect ( ()=>{

return ()=>{console.log(‘this will work as componentWillUnmount’); }

}, [ ])

Hooks for redux

Same as react, react-redux library also provide some of the hooks to ease redux implementation. Let’s see them -

useSelector

It is used to provide redux store to react functional components. Earlier we used mapStateToProps with connect method in order to get state from redux.

const postsList = useSelector(store => store.posts.postsData)

As you can see in above example useSelector accepts a callback that contains store as a parameter and we can choose desired data to return from it. Here we have taken postData from store as a postsList then we can use it to display using map.

useDispatch

It is used to dispatch an action directly from react component. Earlier we need to use either dispatch from connect or mapDispatchToProps with the help of bindActionCreators.

const dispatch = useDispatch();

As you can see in above example useDispatch returns a dispatch function. Here we have dispatched addPost action on click of Add button.

conclusion

hooks makes development easier and simpler with add on of lots of great features in it and provide a better option to class component. It reduces complexity as well as avoids the use of confusing this keyword.

UI Developer @HCL Technologies