Search code examples
javascriptreactjsreact-hooksuse-effect

UseEffect initial state loading


Can somebody explain why does console.log(foodList) return empty array instead of filtered array? I am making pagination logic, and I need to filter array first and then display it. However, this is like side effect and should only be done once because there are some other things which will trigger component re-executing so this has to be in useEffect. Dummy code is just data above this function and you dont have to bother with it.

Function 1

    const correctFunction = () => {
      const pages = Math.ceil(DUMMY_FOOD.length / 5);
    
      const arr = [];
      let helpArr = [];
    
      let c = 0;
    
      for (let i = 0; i < pages; i++) {
        for (let j = c; j < c + 5; j++) {
          helpArr.push(DUMMY_FOOD[j]);
        }
        c += 5;
        arr.push(helpArr);
        helpArr = [];
      }
    
      DUMMY_FOOD = arr;
      return DUMMY_FOOD;
    };

Component

const MenuList = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const params = useParams();
  const [page, setPage] = useState(2);
  let foodList = [];

  console.log(DUMMY_FOOD);
  useEffect(() => {
    foodList = correctFunction();
  }, []);

  console.log(foodList);
  ect...

Solution

  • Effect hooks are run after the render function is complete. If you want to render the result of an effect, use a state. Set it inside the effect to trigger a re-render.

    If you want to do an expensive operation once, then use useMemo instead.

    const foodList = useMemo(correctFunction, []);