React Hooks: useState and useEffect

React Hooks: useState and useEffect

React Hooks: useState and useEffect

React hooks have revolutionized the way we write React components, providing a more intuitive API for managing state and side effects in functional components. Among the most commonly used hooks are useState and useEffect. In this post, we'll dive into these hooks, exploring their usage with practical examples.


Understanding useState


The useState hook allows you to add state to functional components. It returns a stateful value and a function to update it. Here's a simple example to illustrate:


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>
 );
}

export default Counter;


In this example:


  • We import the useState hook from React.
  • We call useState(0) to declare a state variable count with an initial value of 0.
  • We use the setCount function to update the state when the button is clicked.


Exploring useEffect


The useEffect hook allows you to perform side effects in your components. Examples of side effects include data fetching, subscriptions, and manually changing the DOM.


Here's a basic example:


import React, { useState, useEffect } from 'react';

function Timer() {
 const [seconds, setSeconds] = useState(0);

 useEffect(() => {
  const interval = setInterval(() => {
   setSeconds(prevSeconds => prevSeconds + 1);
  }, 1000);

  return () => clearInterval(interval);
 }, []);

 return (
  <div>
   <p>Elapsed time: {seconds} seconds</p>
  </div>
 );
}

export default Timer;


In this example:


  • We initialize a seconds state variable.
  • We use useEffect to set up a timer that increments seconds every second.
  • The cleanup function (return () => clearInterval(interval)) ensures the timer is cleared when the component unmounts, preventing memory leaks.




Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts