简体   繁体   中英

Which option is best for creating new class instance in React functional component?

A general question about creating a new class instance in a React functional component. I'm using Tone.js for a project and the examples here, but relevant for anything.

Between options A and B which is the correct pattern? B is what is commonly seen but if A is incorrect, why? It seems inefficient that if using useEffect, the first render happens and then the instance is created. So your code is full of channels.current && doSomething() . Why can't it be as the useRef initial value?

If a ref keeps its value after a re-render, is useEffect necessary?

And if I want to update the values (4,0) at some point, dynamic values, instead of useRef is it wise to create the class instances as a useState initial value as in option C?

A. As useRef initial value

const channels = useRef({
    channel01: new Tone.Channel(4, 0),
    channel02: new Tone.Channel(4, 0),
    channel03: new Tone.Channel(4, 0)
  });

B. useEffect to initiate ref

const channels = useRef(null);

useEffect(() => {
    channels.current = {
      channel01: new Tone.Channel(4, 0),
      channel02: new Tone.Channel(4, 0),
      channel03: new Tone.Channel(4, 0)
    }
  }, []);

C. As useState initial value

const [channels, setChannels] = useState({
    channel01: new Tone.Channel(4, 0),
    channel02: new Tone.Channel(4, 0),
    channel03: new Tone.Channel(4, 0)
  })

This seems a very opinion based question so obviously everyone's opinion would be different but here are my two cents. The useEffect with no dependencies ie just one time called on mount is generally preferred to populate initial data like from the server as so:

useEffect(()=>{
        axios.get('http://yourserver.com/someendpoint')
            .then(res=>{
                if(res.status === 200){
                    setData(res.data);
                }
            })
            .catch(err=>console.log(err))
    },[]);

Different frameworks have of course developed different ways now like i use next.js alot and in it you can use something like getInitialProps(). But the idea is kinda same.

The best case for you, again in my opinion, would be to use C. Setting data especially defaults is usually done in state so that if you call the state anywhere before it is populated you dont get unexpected errors.

Most importantly React devs universally agree on this convention so in case your code lands on someone else's desk. He/she would be at home with it if say used state to initialize data and useEffect to get initial data from server etc. Again this is an opinion based on years of work and working with developers of react who follow the conventions. Cheers :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM