@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 React, { useState, useEffect } from 'react'; |
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 2 3 4 5 6 |
return ( <div> <p>State value: {stateVariable}</p> <button onClick={() => setStateVariable(newValue)}>Update state</button> </div> ); |
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.