skip to Main Content

I have a next code:

useEffect(() => {
    doSearch();
    console.log(searchParams).
}, [searchParams]);

doSearch function fired twice because useEffect also fired twice. im sure that i dont change searchParams
Components looks like

export default function SearchComponent({ params, searchParams }) {
  useEffect(() => {
    doSearch();
    console.log(searchParams); // there all search params available on both cases so i cant check params on this step...
  }, [searchParams]);

  const doSearch = () => {//some actions}
}

Why its fired twice?

2

Answers


  1. Chosen as BEST ANSWER
    const initialized = useRef(false)
    
    useEffect(() => {
      if (!initialized.current) {
        
    
        // My actual effect logic...
        ...
      } else {
        initialized.current = true
      }
    }, [searchParams])
    

    From React Hooks: useEffect() is called twice even if an empty array is used as an argument Solve my issue


  2. Are you using React 18 in StrictMode? And are you talking about development mode?

    Because effects firing twice in <React.StrictMode /> was added in React 18.

    It is a feature during development mode to make sure you don’t have unexpected side effects, etc:

    StrictMode currently helps with:

    • Identifying components with unsafe lifecycles
    • Warning about legacy string ref API usage
    • Warning about deprecated findDOMNode usage
    • Detecting unexpected side effects
    • Detecting legacy context API Ensuring reusable state

    You can read more about it here:
    https://legacy.reactjs.org/docs/strict-mode.html#ensuring-reusable-state

    Also discussed in one issue on Next.js Github Repo:
    https://github.com/vercel/next.js/issues/35822

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search