Working with useState, useEffect, and other built-in hooks

When developing applications with ReactJS, developers can take advantage of hooks to manage state, side-effects, and other functionalities in a more concise and organized way. Some of the most commonly used built-in React hooks include useState, useEffect, useContext, and useRef. In this article, we'll explore how to work with these hooks and understand their benefits.

useState

The useState hook allows developers to introduce state management within functional components. It provides a way to declare and update state variables while leveraging the simplicity of a functional approach. To use this hook, you must import it from the react package:

import React, { useState } from 'react';

useState accepts an initial value and returns an array with two elements: the current state value and a function to update it. Let's consider an example:

const Counter = () => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

In the code snippet above, we declare a state variable count and a function setCount to update it. Whenever the button is clicked, the increment function is called, which updates the state value by incrementing it.

useEffect

The useEffect hook allows developers to perform side-effects within functional components. Side-effects can include data fetching, subscriptions, or manually changing the DOM. Similar to useState, you need to import useEffect from react:

import React, { useEffect } from 'react';

useEffect takes two arguments: the first one is a function that represents the side-effect, and the second one is an optional array of dependencies. By passing an empty array, [], you can ensure the side-effect only runs once when the component mounts:

useEffect(() => {
  // side-effect code here

  return () => {
    // cleanup code here (optional)
  };
}, []);

If you pass a value or variable in the dependencies array, the effect will re-run whenever that value changes:

useEffect(() => {
  // side-effect code here

  return () => {
    // cleanup code here (optional)
  };
}, [dependency]);

Remember that if the cleanup code is necessary, you can return a callback function in the useEffect function. This cleanup function will be executed before the component unmounts or before running the next effect. It can be used to clean up timers, subscriptions, or any resource allocation performed by the component.

useContext

The useContext hook allows developers to access context values from a React context without wrapping the component with a context provider. To use this hook, import useContext from react:

import React, { useContext } from 'react';

useContext accepts a single argument, which is the context object itself. It returns the current value provided by the context:

const ThemeContext = React.createContext();

const MyComponent = () => {
  const theme = useContext(ThemeContext);

  // ...
};

By calling useContext(ThemeContext), our component receives the current theme value provided by the ThemeContext context.

useRef

The useRef hook provides a way to create mutable variables that persist across renders. Unlike state variables which trigger re-renders, useRef allows us to store and preserve values without causing re-rendering. The import statement for useRef is similar to the previous hooks:

import React, { useRef } from 'react';

To create a ref variable, we can use the useRef hook:

const inputRef = useRef();

The inputRef can be used to reference any HTML element or to store any other mutable value. It persists throughout the component's lifecycle and allows us to access and manipulate its properties directly.

Conclusion

The built-in hooks useState, useEffect, useContext, and useRef provide powerful tools to handle state, side-effects, context values, and mutable variables in a functional manner. Incorporating these hooks in your ReactJS projects will simplify and enhance your development experience, enabling you to build more maintainable and performant applications.


noob to master © copyleft