DEV Community

Onkar Deshpande
Onkar Deshpande

Posted on

'___' is most popular hook in ReactJs ?

Before we reveal the most popular hook ( the secret is already out , it's useState !), lets try and understand what are React hooks and why do we need them in the first place?

Hooks are basically functions which help you hook into the React state in functional components. If you are new to React, just know that this hooks basically helped decrease the lines of code written significantly !

Here is an example of class based components, which was the default way to write components before React 16.8 (2018) (this was when React hooks were released)

The old way :

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

The new way :

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

React Hooks made React developers lives easier , hence made React's learning curve much less steeper , increasing it's popularity.

And , the most popular hook used in ReactJs is .....

useState() !

Surprise but no surprise!

In simple language, useState is a way to store and use , any kind of data in our react component.
Above , we saw the the example of how useState works as a counter.

Few points to remember about useState :
const [counter ,setCounter] = useState(0)

  1. It uses array destructuring to get two things. The data (counter), and a function to set the data (setCounter).
  2. You can use the counter directly in your JSX code like so : {counter}
  3. You can use the setCounter function to set data to the state like so : setCounter(10)
  4. You can also use Objects or arrays as the data in the useState, making it a powerful tool to render out data.

Here are 3 examples of useState() to make our understanding of useState ironclad.

1.Color selector :
Use the state to change color of the text :

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [textColor, setTextColor] = useState("");
  return (
    <div className="App">
      <h1 style={{ color: textColor }}>Hello CodeSandbox</h1>
      <button onClick={() => setTextColor("red")}>Red</button>
      <button onClick={() => setTextColor("blue")}>Blue</button>
      <button onClick={() => setTextColor("green")}>Green</button>
      <button onClick={() => setTextColor("black")}>Reset</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

See the result

2.List rendering and updating using state :

import { useState } from "react";
import "./styles.css";

export default function App() {
  const data = [
    { name: "Onkar", age: 28 },
    { name: "Tushar", age: 24 },
    { name: "Amira", age: 29 }
  ];
  const [userData, setUserData] = useState(data);
  const removeHandler = (obj) => {
    setUserData(userData.filter((person) => person !== obj));
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <ul>
        {userData.map((obj) => (
          <li>
            {obj.name} is of the age {obj.age}{" "}
            <button onClick={() => removeHandler(obj)}>remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

See the results

3.Using state to use Dark mode for an app:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [theme, setTheme] = useState("");
  return (
    <div className="App">
      <div className={`app-container ${theme}`}>
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <button onClick={() => setTheme("dark")}>Switch to Dark mode</button>
        <button onClick={() => setTheme("")}>Switch to Light mode</button>
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

See the results


I hope you now have a fair Idea of how the useState hook works and are going to be able to use the hook in your beginner journey of being a FrontEnd Developer !

You can always contact me on twitter !

Happy Hacking !

Discussion (2)

Collapse
andrewbaisden profile image
Andrew Baisden

React hooks are so much better than classes it would be hard to go back to classes for any modern projects now. Only legacy codebases.

Collapse
i_am_onkar profile image
Onkar Deshpande Author

I agree. As a new student of React I am greatful to land into this when hooks exist :)