Ricardo Lopes
Ricardo Lopes

Reputation: 149

React Hook "useState" is called conditionally

React is complaining about code below, saying it useState and useEffect are being called conditionally. The code work's fine without typescript:

import React, { useState, useEffect } from "react";

const useScrollPosition = () => {
  if (typeof window === "undefined") return 500;

  // Store the state
  const [scrollPos, setScrollPos] = useState(window.pageYOffset);

  // On Scroll
  const onScroll = () => {
  setScrollPos(window.pageYOffset);
};

  // Add and remove the window listener
  useEffect(() => {
    window.addEventListener("scroll", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
    };
  });
};

export default useScrollPosition;

Upvotes: 2

Views: 725

Answers (2)

Ramin eghbalian
Ramin eghbalian

Reputation: 2667

move the return to bottom of function and pass empty array to second parameter of useEffect for exists code in the useEffect run only once time.

import React, {useState, useEffect} from "react";

const useScrollPosition = () => {
    

    // Store the state
    const [scrollPos, setScrollPos] = useState(window.pageYOffset);

    // On Scroll
    const onScroll = () => {
        setScrollPos(window.pageYOffset);
    };

    // Add and remove the window listener
    useEffect(() => {
        window.addEventListener("scroll", onScroll);
        return () => {
            window.removeEventListener("scroll", onScroll);
        };
    }, []); // set an empty array for run once existing code in the useEffect

   return typeof window === "undefined" ? return 500 : <></>; // a value must be returned
    
};

export default useScrollPosition;

Upvotes: 1

topched
topched

Reputation: 765

You have an early return so it is being called conditionally if (typeof window === "undefined") return 500;

You need to move the hooks before the early return. For a detail explanation read this https://reactjs.org/docs/hooks-rules.html

Upvotes: 3

Related Questions