3

I want to do a debounce for custom input, but my problem is I can't stop useEffect from trigger on initial render

import { useDebouncedCallback } from "use-debounce"; interface myInputProps { getValue: any; } const MyInput = ({ getValue }: myInputProps) => { const [value, setValue] = useState(""); React.useEffect(() => { getValue(value); }, [value]); return ( <input type="text" value={value} onChange={e => setValue(e.target.value)} /> ); }; export default function App() { const [debouncedCallback] = useDebouncedCallback(value => { console.log(value); }, 1000); return ( <div className="App"> <MyInput getValue={debouncedCallback} /> </div> ); } 

https://codesandbox.io/s/upbeat-lamport-ukq70?file=/src/App.tsx

I've also tried useLayoutEffect but it doesn't solve the problem.

1
  • did you try using useRef? Commented Apr 10, 2020 at 7:34

2 Answers 2

4

We could use useRef to keep track of if it's the first time the useEffect hook is being run.

https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables

Sandbox link: https://codesandbox.io/s/confident-cerf-flkf2?file=/src/App.tsx

 const MyInput = ({ getValue }: myInputProps) => { const [value, setValue] = useState(""); const first = useRef(true); React.useEffect(() => { if (first.current) { first.current = false; return; } getValue(value); }, [value]); return ( <input type="text" value={value} onChange={e => setValue(e.target.value)} /> ); }; 
Sign up to request clarification or add additional context in comments.

1 Comment

It is not gonna work if you wanted it to reset the first on page reload/refresh. Any suggestion? like to let it to tell you that this is the first time that it rendered the component but after that as long as you have not refreshed the page it should not change it to true. But if you refreshed/reload the page it is gonna change to true. But right now it is not like that (I tested it)
0

Set initial value to undefined and you can explicitly check for undefined. Once the user enter, it won't be undefined.

const MyInput = ({ getValue }: myInputProps) => { const [value, setValue] = useState(undefined); React.useEffect(() => { if (value === undefined) { return; } getValue(value); }, [value]); return ( <input type="text" value={value} onChange={e => setValue(e.target.value)} /> ); }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.