skip to Main Content

I’m a bit baffled by the logic behind react useEffect and custom hooks.

I have a useEffect call that is only called once on load. It has tons of variables that are disposed after the first use. I tried to split it up into several custom hooks.

Current huge code:

function App() {
  useEffect(()=>{
    // tons of code to load and parse a CSV
    ...
    // tons of code to create a drawing from the csv
    ...
    // tons of code to appy an algorithm to the csv data
    ...
    // finished. show a result. never use the data / drawing again.
  },[])
}

My expectation for using custom hooks:

function App() {
  useEffect(()=>{
    let data = useCSVLoader()
    let drawing = useDrawing(data)
    let algorithm = createAlgorithm(data)
  },[])
}

But according to the documentation I HAVE to put the custom hooks in the main function body? But since they are dependent on each other, how do I know they are called in the right order? Does each custom hook need an internal useEffect?

Would the following assumption be correct?

function App {
    let data = useCSVLoader()
    let drawing = useDrawing(data)
    let algorithm = createAlgorithm(data)
    useEffect(()=>{
       // nothing here anymore?
    },[])
}

2

Answers


  1. if the data is async you could something like this

    function App {
        const [csvData,setCsvData] = useState() 
        let data = useCSVLoader()
        let drawing = useDrawing(csvData)
        let algorithm = createAlgorithm(csvData)
    
        useEffect(()=>{
           if(data) {
            setCsvData(data)
           }
        },[data])
    }
    

    so when the data is available it triggers the useEffect and sets the data when the data is available

    in the custom hook where you get the prop data check for the presence of data like this so we can prevent unwanted renders

    useEffect(()=>{
       if(!props.data) { return }
       // write your logic
    },[props.data])
    
    Login or Signup to reply.
  2. Your can return functions from your custom hooks useDrawing and useCreateAlgorithm that will be called in the main useEffect when data is available, something like this:

    const useDrawing = () => useCallback((data) => { 
      // your logic here
    }, []);
    
    const useCreateAlgorithm = () => {
      const [state, setState] = useState();
      return useCallback((data) => {
        // your logic here
      }, []);
    }
    
    function App {
        let data = useCSVLoader()
        let drawingFn = useDrawing();
        let algorithmFn = useCreateAlgorithm();
    
        useEffect(()=>{
          if(data) {
            const drawing = drawingFn(data);
            const algorithm = algorithmFn(data)
          }
        },[data, drawingFn, algorithmFn]);
    
        ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search