How to use the prop value inside a useEffect without adding it to the dependency array?

Viewed 43

I have a scenario like this. Both message and level are coming from props. But I need to log the level only on message value change and when message=== 'data', but not on level change. How can I achieve that? I implemented the useEffect hook like this. But it's giving me this eslint warning React Hook useEffect has a missing dependency: 'level'. Either include it or remove the dependency array. . So, what's the best way to get this fixed ?

useEffect(() => {
    if (message === 'data') {
        console.log('level : ', level);
    }
}, [message]);
1 Answers

You can use useRef hook to prevent the warning

  const levelRef = useRef('');

  useEffect(() => {
    levelRef.current = level;
  }, [level]);

  useEffect(() => {
    if (message === 'data') {
      console.log(levelRef.current);
    }
  }, [message]);

or disable the eslint in this line

   useEffect(() => {
       if (message === 'data') {
           console.log(level);
       }
   }, [message]); // eslint-disable-line react-hooks/exhaustive-deps
Related