How do you access react hooks in multiple components? What am I doing wrong with my react hook?

1.7k views Asked by At

Im trying to pass a state value into a component. Why is it working in one component and not working in another component in the same folder?

I have the hooks in here. Im trying to access "currentGuess". In this function I initialize the state of currentGuess to "", then the next part just sets the "currentGuess" to whatever you type in.

----------------------/src/hooks/useWordle.js----------------------

const useWordle = (solution) => {
  const [currentGuess, setCurrentGuess] = useState("");

  /* OTHER UNNECESSARY CODE TO QUESTION */

  const handleInput = ({ key }) => {
    if (key === "Enter") {
      if (turn > 5) {
        console.log("You used all your guesses!");
        return;
      }
      if (history.includes(currentGuess)) {
        console.log("You already tried that word!");
        return;
      }
      if (currentGuess.length !== 5) {
        console.log("Word must be 5 characters long!");
        return;
      }
      const formatted = formatGuessWord();
      console.log(formatted);
    }
    if (key === "Backspace") {
      setCurrentGuess((state) => {
        return state.slice(0, -1);
      });
    }

    if (/^[a-zA-z]$/.test(key))
      if (currentGuess.length < 5) {
        setCurrentGuess((state) => {
          return state + key;
        });
      }
  };
  return {
    currentGuess,
    handleInput,
  };
};

export default useWordle;

I can use it in here like this and it works no problem:

----------------------src/components/Wordle.js----------------------

import React, { useEffect } from "react";
import useWordle from "../hooks/wordleHooks.js";

function Wordle({ solution }) {
  const { currentGuess, handleInput } = useWordle(solution);
  console.log("currentGuess=", currentGuess);

  useEffect(() => {
    window.addEventListener("keyup", handleInput);

    return () => window.removeEventListener("keyup", handleInput);
  });

  return <div>Current guess: {currentGuess}</div>;
}

export default Wordle;

I thought this line was what allowed me to use "currentGuess". I destructured it.

const { currentGuess, handleInput } = useWordle(solution);

However when I place that line in this code, "currentGuess" comes out undefined or empty.

----------------------/src/components/Key.js----------------------

import React, { useContext } from "react";
import { AppContext } from "../App";
import useWordle from "../hooks/wordleHooks.js";

export default function Key({ keyVal, largeKey }) {
  const { onSelectLetter, onDeleteKeyPress, onEnterKeyPress } =
    useContext(AppContext);
  const { currentGuess } = useWordle();

  const handleTypingInput = () => {
    console.log("Key.js - Key() - handleTypingInput() - {currentGuess}= ", {
      currentGuess,
    }); // COMES OUT "Object { currentGuess: "" }"
  };

If you made it this far thank you very much. Im new to this and hoping someone who knows what they are doing can see some glaring flaw in the code I can fix. You don't even have to solve it for me but can you point me in the right direction? How do I make the "currentGuess" variable/state be accessible in the Key.js component?

1

There are 1 answers

3
Brendan Bond On

Hooks are meant to share behavior, not state. The call to useWordle in your Wordle component creates a completely different variable in memory for currentGuess than the call to useWordle in the Key component (remember, after all, that hooks are just regular old functions!). In other words, you have two completely separate versions of currentGuess floating around, one in each component.

If you'd like to share state, use the Context API, use a state management library (such Redux, MobX, etc.), or just lift state up.