4
votes

I have some multiple states and functions to set the state using useState hook.

on each setstate component gets re-render. I want to re-render only functions of setstate fully completed.

for example:

in app.js

const [a, setA] = useState(() => false);
const [b, setB] = useState(() => {});
const [c, setC] = useState(() => props.c);
const [d, setD] = useState(null);
const [e, setE] = useState(null);
const [f, setF] = useState(null);
const [g, setG] = useState('');

const func1 = useCallback(data => {
  setA(true);
  setB(true);
  setC(data && data.c);
  setD();
  setE(isChecked ? 'a' : 'b');
}, []);

const func2 = useCallback(data => {
  setA(false);
  setB(false);
}, []);

const func3 = useCallback(data => {
  setC(false);
  setD(false);
}, []);

const events = {
  func1,
  func2,
  func3
};

const handleMessage = e => {
  const { eventName, data } = e.data;
  const handleEvents = eventName ? events[toCamel(eventName)] : null;
  if (handleEvents && typeof handleEvents === 'function') {
    handleEvents(data);
  }
};

useLayoutEffect(() => {
  iframe.addEventListener('message', handleMessage, true);
  return () => {
    iframe.removeEventListener('message', handleMessage, true);
  };
}, []);

return (
 <Fragment>
  {a && (
    Component1
  )}
  {b && c && (
    Component2
  )}
</Fragment>

);

On each func1 and func2 setA and setB return statement rerender the element. I don't want to re-render on each setA,setB,setC etc. once func1 or func2 fully completes only want rerender the components. As am new to hooks, can someone help with this?

2

2 Answers

1
votes

if your state values are so deeply connected and you want to make sure everything is updated at once:

const [state, setState] = useState({
  a: () => false,
  b: () => {},
  c: () => props.c,
  d: null,
  e: null,
  f: null,
  g: ''
});

const updateState = newState => setState(Object.assign({}, state, newState));

now when you want to update your state just use updateState like this:

const func1 = useCallback(
  (data) =>
    updateState({
      a: true,
      b: true,
      c: data && data.c,
      d: undefined,
      e: isChecked ? 'a' : 'b',
    }),
  [],
);
1
votes

you can store all your variable in one state like this:

const [state,setState] = useState({ a:false, b:{}, c:props.c,d:null})

const func1 = useCallback(data => {
setstate({a:true,b:true,c:data && data.c,d:null})
}, []);