Conteúdo do curso
React.js: Understand and Apply the Lifecycle
Sobre a Aula

useState and useEffect

Hooks useState and useEffect are fundamental for functional components in React. They help add state and manage side effects, respectively.

useState

The useState hook allows you to add state to a functional component. It returns a pair: the state value and a function to update it. Here’s how to use it:

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 here
      </button>
    </div>
  );
}

In the example above:

  • useState(0) initializes the state with the value count 0.
  • setCount is the function used to update count.
  • Each time the button is clicked, setCount increments the value of count.

useEffect

The useEffect hook allows you to perform side effects in functional components. It is called after rendering. With it, you can, for example, fetch data, update the DOM, or set timers.

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>Seconds: {seconds}</p>
    </div>
  );
}

In this example:

  • useState(0) initializes the state with seconds 0.
  • useEffect sets up an interval that increments seconds every second.
  • The cleanup function clearInterval() is used to clear the interval when the component unmounts.

Conclusion

Hooks useState and useEffect are essential for functional components in React. useState adds state and useEffect manages side effects. With them, you can create dynamic and interactive components simply and effectively.

Entrar na conversa
Rolar para cima