Hooks and functional component in React js

Krantibrid
5 min readSep 28, 2020

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Why hooks?

React library provides us hooks which can be used to implement various functionalities in functional components.

  • classes can be confusing and could easily be used incorrectly (e.g. wrong usage of lifecycle)
  • Hooks are going to make sharing logic between components very easy
  • Hooks lets us use state, lifecycle, context system, ref system etc in functional components.

Following are few hooks that can be imported from React library and their uses

1. Using state in Functional component ( useState ) (only available in React > 16.8)

useState() is a Hook. It’s provided by React’s core API and you use it to manage state in functional components.

The way it works is like this:

  1. You pass in your initial state ([ ])
  2. It returns an array with exactly 2 elements ([resource, setResource] => your current state and a state-setting function)
  3. You access the state with the first element and set it with the second element (which is a function)

Syntax :

const [currentValue, setCurrentValue]=useState(initialValue)

currentValue: Contains the present value of this piece of state (same as this.state.<stateKey>)
setCurrentValue: Function to call when we want to update our state (and render) (same as this.setState({…}) )
useState: Function imported from React library
initialValue: Starting value for this piece of state similar to when we initialise our state object (same as this.state = {…} )

Example
Consider a simple class component that makes use of state and changes the state’s value as per the button clicked

class Content extends Component {
state = { resource: 'post' }
render() {
return <div className='contentWrapper'>
<div>
<button onClick={() => this.setState({resource: 'post'})}>POSTS
</button>
<button onClick={() => this.setState({resource: 'todo'})}>TO DO'S</button>
</div>
{this.state.resource}
</div>
}}

This class based component can be converted to functional component as

import React, { useState } from 'react'
const Content = () => {
const [resource, setResource] = useState('post')
return (
<div className='contentWrapper'>
<div>
<button onClick={() => setResource('post')}>POSTS</button>
<button onClick={() => setResource('toDo')}>TO DO'S</button>
</div>
{resource}
</div>
)
}

Each state will be independent of the other states and updating one state will therefore have no impact on the others.
State can be anything when using React Hooks: An array, an object, a number, a string or a boolean.

2. Using lifecycle methods in Functional component ( useEffect )

Besides useState(), there’s another “core React Hook”: useEffect().
useEffect() takes a function as an input and returns nothing.
The function it takes will be executed after every render cycle i.e it gets called every time our component gets rendered
This leads to an issue that the function inside of useEffect() gets executed unnecessarily (i.e. whenever the component re-renders).
This issue is solved by the second parameter ([ ]) that useEffect() accepts.

ComponentDidMount()

useEffect(() => { ... }, [])

The second parameter passed here is an empty array. This indicates that the useEffect function will be called only once in the entire lifecycle of the component.

componentDidUpdate()

useEffect(() => { ... }, [dependency1, dependency2])

Limit execution to the change of certain dependencies (comparable to manual diffing/ if checks in componentDidUpdate)

Alternatively,if you want to run your effect on every re-render cycle:

useEffect(() => { ... })

componentWillUnmount ()

useEffect(() => {
const timer = setTimeout(() => {
// do something amazing here
}, 2000)
return () => {
// Cleanup work goes in here
clearTimeout(timer)
}
})

The function passed as a first argument to useEffect() can return another function. If you return a function, that function will be executed before the component is removed from the DOM. Therefore, this returned function is the perfect place for cleanup work.

useState() and useEffect() are by far the two most important ones and the two Hooks that you really need to write functional components everywhere (instead of class-based ones).

3. Using Context in Functional component ( useContext )

useContext accepts a context object ( the value returned from React.createContext ) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider>.

A component calling useContext will always re-render when the context value changes

In Hooks, useContext(MyContext) is equivalent to
static contextType = MyContext in a class, or to MyContext.Consumer> .

static contextType = languageContext;

Is same as writing the below code in functional component

const selectedLanguage = useContext(languageContext);

4. Using Hooks in a React Redux

Redux can be cumbersome because of wiring it using connect function or to map the state to props. Using hooks, this task becomes easier.

useSelector()
Allows you to extract data from the Redux store state, using a selector function.
The selector is approximately equivalent to the mapStateToProps argument to connect conceptually. The selector will be called with the entire Redux store state as its only argument. The selector will be run whenever the function component renders

const post = useSelector(state => state.post);

Thus the variable post is set to the state defined from their respective reducers.

useDispatch()
This hook returns a reference to the dispatch function from the Redux store. You may use it to dispatch actions as needed. The equivalent of mapDispatchtoProps is useDispatch.

const dispatch = useDispatch();
dispatch({action object})

5. useReducer()
useReducer is a Hook built-into React and it helps you with state management.
It is an alternative to useState.
useReducer() takes two arguments:

  • A reducer function (which in turn receives the state and an action as arguments)
  • An initial state

The reducer function works like a reducer function you know from Redux.

  • It receives the current state as an input and should return the updated state. To do that, it also receives an action that describes the desired state update.
  • useReducer() then returns an array with exactly two elements: The state and a dispatch function that allows you to “send a new action to the reducer”.
const [state, dispatch] = useReducer(reducer, initialState)

Although there are no middleware with useReducer so Redux should be used at times

Hooks makes the task of using functional components work as class components very simple. In case of any doubts, its always good to refer the official document for solutions.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response