Home > database >  Clean react useState in useEffect
Clean react useState in useEffect

Time:11-28

im trying to clean the state every time the effect is called, here is my code

const [id,setNodos] = useState([]);

useEffect(() =>{
    {props.data.channel.map((canales,i) => (
        setNodos(prevState => [...prevState, {channelId: canales.channelId, x:(dimensions.width/4)*Math.cos(2 * Math.PI * ((i/ props.data.channel.length)  0.75))}])
))}
},[props.data])

I want to clean id every time useEffect is triggered.

CodePudding user response:

Since the state is stored in id and you have its setter setNodos, you can simply set its state back to the original state [] like this: setNodos([]);. Or if that's not what you mean with "clean", then you simply have to write the logic yourself.

CodePudding user response:

You shouldn't update state on for each node. This is not optimized. Theoretical each setState runs component rerender. But react probably will optimize this operation and don''t rerender compoent unitl useEffect will end.

You should map your data to 'nodos' array and the set it.

And there is convenion. if you have setNodos the 'id' should be named 'nodos'.

    const [id,setNodos] = useState([]);

    useEffect(() =>{
        const nodes = props.data.channel.map((channel,i) => ({
            channelId: channel.channelId, 
            x:(dimensions.width/4)*Math.cos(2 * Math.PI * ((i/ props.data.channel.length)  0.75))
        }))
        setNodos(prevNodes => ({
            ...prevNodes,
            ...nodes
        }))
    },[props.data, dimensions, setNodos])

ps. you can install some spell checker in IDE.

  • Related