How do I use useEffect?

Hi, I could do with some help with this one in the coding challenges - I want the console to transmit the length of characters in both the first name and last name respectively, in the code below. Thanks!

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

function Output() {
  const [firstName, setFirstName] = useState("");
  const [firstNameLength, setFirstNameLength] = useState(0);

  //first useEffect hook
  useEffect(() => {
    const firstLength = firstName.length;
    const fnName = () => {
      setFirstNameLength(firstNameLength + 1);
    }, []);

  const [lastName, setLastName] = useState("");
  const [lastNameLength, setLastNameLength] = useState(0);

  //second useEffect hook
  useEffect(() => {
    const lastLength = lastName.length;
   const lName = () => {
      setLastNameLength(lastNameLength + 1);
  }, []);

  return (
      <h4>Type your name below</h4>
      <h5>First Name</h5>
      <input type="text" onChange={(e) => setFirstName(} />
      <h5>Last Name</h5>
      <input type="text" onChange={(e) => setLastName(} />
        Your first name is {firstName} and it is {firstNameLength} letters
        Your last name is {lastName} and it is {lastNameLength} letters

ReactDOM.render(<Output />, document.getElementById("app"));

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

You declare the variable firstLength but never use it. And why do you increment the length?
Also why do you declare a function fnName (which you never call) rather than just calling the state setter in the effect hook directly?

From what I understand you could just do this:

useEffect(() => {
    const firstLength = firstName.length;
  }, [firstName]);

Also your effect hook needs a dependency: firstName since you refer to that value inside the hook.

Lastly, you don’t need an effect hook, but you could set the state firstNameLength and lastNameLength in the onChange callback function.

1 Like

Thanks! Unfortunately, the length count doesn’t go up still

Can you post your updated code, please?