React tutorial – Understanding React Hooks with examples

In this tutorial, we will understand what are hooks and why they are being used widely.

React Hooks

Hooks are new functionality added to react. They let you use state and other features of react without writing any class. Hooks don’t work inside classes, they let you use React state without using classes. Stateful components are the component which has a state and which are defined in a class. These component also have lifecycle method like: componentDidMount(),render() etc.

You can’t use any of this in a stateless component or functional component. Function component in React does not have their own state and don’t have any life cycle. They only act upon data that are passed to them as props.

But with React hooks now you can. What Reacts hooks do is it allow us to take a React functional component and add state to it. Hooks are special function which extends the capabilities of React’s functional component and gives them the capability to add state and lifecycle to it.

Now let’s take a simple example, to see how React hooks works :

import React from 'react';
import './App.css';

function App() {
    
  const [count,setCount] = React.useState(0);

  return (
    <div className="App">
      <h1> {count} </h1>
      <button onClick={() => { setCount( count + 1) } } >
          Click Me!
      </button>
    </div>
  );
}

export default App;

Here I have written a function component called App. In this function, I have used a React.useState() hook. The useState() hooks are mainly used to store the state of the function component. This useState() returns a pair which are the current state value and the function which is used to update that value. This is very much similar to this.setState of a class component. React.useStaterequired only on an argument which is the initial value of the state. Here the initial value of the state count is 0.

Besides useState hooks React also provide the following hooks:

useEffect

This hook is used for fetching data or manually changing the DOM, etc. It gets executed for 3 different lifecycles of React componentDidMount,componentDidUpdate,componentWillUmount in React class. By default, React runs useEffect function after every render.

Below I have written a component which will change the message from the screen a second after component gets mounted.

import React from 'react';
import './App.css';

function App() {
    
  const [msg,setMessage] = React.useState("Before compoent gets mounted");
  React.useEffect( () => {
      setTimeout(() => {
          setMessage("A second after component mounted");
      },5000);
  });

  return (
    <div className="App">
      <h1> {msg} </h1>
    </div>
  );
}

export default App;

Output:

React tutorial - Understanding React Hooks with examples
Before

 

React tutorial - Understanding React Hooks with examples
After

 

Just you can do clean up using componentWillUmount in the stateful component you can also perform this operation with useEffect. We do this by returning function.

  React.useEffect( () => {
      SomeAPI.subscribe(props.friend.id, handleStatusChange);

    return () => {
      SomeAPI.unsubscribe(props.friend.id, handleStatusChange);
    };
  });

useContext

This is used in conjunction with React Context API. They let you subscribe to the React context without introducing nesting in the component.

function App() {
    const locale = useContext(Locale);
    const theme = useContext(Theme);
    
}

useReducer

An Alternative of useState hook used when you have complex state logic. They are used to manage the local state of the complex components.

import React from 'react';
import './App.css';

const count = 0;
const reducer = (state,action) => {
    switch(action) {
        case '+' : return state + 1;
        case '-' : return state - 1;
        case 'reset' : return 0;
    }
}
function App() {
    const [state,actionFun] = React.useReducer(reducer,count);
    return (
        <div className = "App">
        <h1> { state } </h1>
            <button onClick = {() => actionFun('+')}> Add </button>
            <button onClick = {() => actionFun('-')}> Sub </button>
            <button onClick = {() => actionFun('reset')}> Reset </button>
        </div>
    )
}

export default App;

Rules for using Hooks

  • Only call hooks from the top level. That is don’t call hooks inside loops, conditions or nested function.
  • Don’t call hooks from a regular javascript function. Hooks should only be called from React function.
  • You may call the hooks from other hooks

Sharing is caring!

Leave a Comment

Your email address will not be published. Required fields are marked *

shares
Scroll to Top