Search⌘ K

Which Hooks Should We Know?

Explore the fundamental React hooks useState and useEffect to manage state and side effects within functional components. Understand how these hooks replace class components for better state handling, learn about controlling side effects with dependency arrays, and see practical examples in a simple social media app context.

What are hooks, and why use them?

Stateless components are generally easier to write and test. They should be the go-to component of ReactJS developers, but they were often overlooked because they could not manage state. At the beginning of 2019, the ReactJS team added hooks to the library. Hooks add state functionality to stateless components (therefore, it is better to only use the term functional components). One specific hook called useState is a function that returns a stateful value and a function to update it.

Let’s go back to our example of a stateful component, change it to a functional one, and add the useState hook, as follows:

Click the “Run” button below to see it running successfully:

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "expo": "~48.0.18",
    "expo-status-bar": "~1.4.4",
    "react": "18.2.0",
    "react-native": "0.71.8",
    "expo-constants": "~14.2.1",
    "@expo/vector-icons": "^13.0.0",
    "react-native-paper": "4.9.2"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0"
  },
  "private": true
}
Example of functional component with useState

We still have a component capable of holding and managing state changes, but it’s much shorter than the stateful class component. This type of component has a very nice logical flow, where we declare the state value and the state setter function on one line, as shown in line 5.

The first hook we spoke about was ...