How to use React hooks (e.g., useState, useEffect)?

Member

by orpha , in category: Javascript , 7 months ago

How to use React hooks (e.g., useState, useEffect)?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 7 months ago

@orpha 

React hooks, such as useState and useEffect, allow you to add state and side effects to your functional components in React. Here's a step-by-step guide on how to use them:

  1. Import the required hooks from the 'react' package:
1
import React, { useState, useEffect } from 'react';


  1. Declare a functional component and use the useState hook to add a state variable and its setter function:
1
2
3
4
5
6
7
function MyComponent() {
  const [stateVariable, setStateVariable] = useState(initialValue);
  // ...
  return (
    // JSX code goes here
  );
}


In the above code, 'initialValue' is the initial value for the state variable, and 'stateVariable' is the current value of the state. 'setStateVariable' is the function that can be used to update the state.

  1. Use the state variable and its setter function in your component's JSX code:
1
2
3
4
5
6
return (
  <div>
    <p>State value: {stateVariable}</p>
    <button onClick={() => setStateVariable(newValue)}>Update state</button>
  </div>
);


  1. Use the useEffect hook to add side effects, such as fetching data, subscribing to events, or manipulating the DOM. The useEffect hook takes two parameters: a callback function and an optional array of dependencies. The callback function will be called after the component renders, and whenever the dependencies change:
1
2
3
4
5
6
7
8
useEffect(() => {
  // Side effect code goes here
  // ...
  return () => {
    // Cleanup code goes here (optional)
    // ...
  };
}, [dependency1, dependency2]);


The cleanup function is optional and can be used to clean up any resources used by the side effect.


Note: Hooks should always be used at the top level of the functional component and should not be used inside loops, conditions, or nested functions.


By using useState and useEffect hooks, you can easily add and manage state and side effects in your functional components in React.