Home > database >  Basis of two props wanted to update single state value without useEffect
Basis of two props wanted to update single state value without useEffect

Time:12-09

What is the best way to update single state value, if specific two props changes, without useEffect, since performance point of view we should not be setting state inside useEffect.

For Example:

const NestedList = ({childItems, parentItems, selected, ...rest}) => {
  const [currentItems, setCurrentItems] = useState({}); //assume this could be hash object 
  
  // Wrong X
  useEffect(() => setCurrentItems(parentItems), [parentItems])

  // Wrong X
  useEffect(() => setCurrentItems(childItems), [childItems])

  return ...

CodePudding user response:

React component updates on both State change and Prop change. So you don't have to do anything additonal

CodePudding user response:

Try below in single use effect. You can also compare previous props with new props.

useEffect(() => { setCurrentItems(whateverthevalueis) }, [prop1,prop2]);

CodePudding user response:

What i try to figure out is the why in this case. Why do you need a state if you always want to change it? Why do the two props replace each other in the state?

There is nothing wrong with setting the state in a useEffect as alot of people already have said. However useEffect should be used for side effects.

There is no golden solution for all cases.

Use a state if you set the intial state with props and then the component update the state itself.

const processItems = (childItems, parentItems, ) => {
    // Do what you want to create one state
    return childItems 
}

const NestedList = ({childItems, parentItems, selected, ...rest}) => {
    // use props to set the inital state
    const [currentItems, setCurrentItems] = useState(processItems(childItems, parentItems))
    // We can later mutate the state, however if the props change we do not care

If the parent always pass the state as a prop, you do not need a state since the state is handled higher up.

const NestedList = ({childItems, parentItems, selected, ...rest}) => {
    // No need for a state here, we can just use the props directly and
    // the parent will pass the updated props when the state changes

If the parent pass several props and you need to calculate stuff based on the props, use memo hook.

const NestedList = ({childItems, parentItems, selected, ...rest}) => {
  
  const currentItems = useMemo(() => {
    // Add the condition of what items to show here 
    if(parentItems.length > 0) return parentItems
    return childItems
  }, [childItems,parentItems])

  return ...
  • Related