×

Introduction

In software development, React is one of the most popular front-end libraries for building user interfaces. React Hooks are introduced in version 16.8 to provide better ways to manage state and side effects in functional components. The most widely used hooks are useState and useEffect to manage state and side effects respectively.

useState: Managing Component State

With useState, functional components can now have their own internal state.

const [state, setState] = useState(initialState);
  • state: The current state of the component.
  • setState: A function used to update the state.
  • initialState: The initial value of the state (e.g., string, number, object).
Example: import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }

useState(0) – initializes count with a value of 0. setCount function updates the count value whenever the button is clicked.

Updating State Based on Previous State

To update the state based on its previous value, pass a function to setState.

setCount(prevCount => prevCount + 1);

This approach helps to ensure that React always has the latest state.

useEffect: Managing Side Effects

Side effects refer to operations that affect something outside the component, such as fetching data, manually updating the DOM and setting up subscriptions. The useEffect hook was designed to handle these operations efficiently.

useEffect(() => { // Side effect code here return () => { // Cleanup code here (optional) }; }, [dependencies]);

Effect function contains the side effect logic. Cleanup functions and Dependencies array are optional. Cleanup functions are return functions, which is called when the component unmounts or before re-running the effect. Dependencies array are an array of values that the effect depends on. The effect is re-run whenever one of these values changes.<.p>

Fetching Data from an API

import React, { useState, useEffect } from 'react'; function DataFetcher() { const [data, setData] = useState([]); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()).then(json => setData(json)); return () => { // Cleanup if needed }; }, []); return ( <ul> {data.map(item => ( <li key={item.id}>{item.title}</li> ))} </ul> ); }

When the component mounts, the useEffect hook runs the fetch operation. The empty dependency array ([]) ensures the effect runs only once, when the component is first rendered.

Cleanup Function

The cleanup function is useful for tasks, such as:

  • Canceling network requests
  • Removing event listeners
  • Clearing timeouts when a component unmounts
useEffect(() => { const timer = setTimeout(() => { console.log('Timeout completed'); }, 3000); return () => clearTimeout(timer); }, []);

clearTimeout ensures that the timer is cleared if the component unmounts before the timeout finishes.

Dependency Array

The dependency array is vital for controlling when the effect runs. If you omit it, it will lead to performance issues.

Empty array ([]): The effect runs only on mount and unmount.

Specific dependencies: The effect re-runs only when one of the dependencies changes.

useEffect(() => { console.log('Name changed!'); }, [name]);

Best Practices of React hooks

Always ensure that the state or props used inside useEffect are declared in the dependency array. If it is not included in the dependency array, it can lead to bugs.
Avoid over usage of useEffect. Not everything needs to be a side effect. Overusing of useEffect can result in unnecessary re-renders and performance degradation.
JavaScript treats new function and object instances as different. So passing functions or objects as dependencies can cause the effect to re-run unnecessarily. To solve this, use useCallback or useMemo to memorize them.

const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);

Conclusion

Finally, React’s useState and useEffect hooks have revolutionized the way of building components by simplifying state management and side effect handling in functional components. Understanding and learning how to use these hooks is a key to write cleaner and more maintainable React code. To master useState and useEffect, join Credo Systemz React JS Training in Chennai. Our live sessions guides you in creating powerful, efficient, and readable applications.

Join Credo Systemz Software Courses in Chennai at Credo Systemz OMR, Credo Systemz Velachery to kick-start or uplift your career path.