Skip to content
Advertisement

How to change useState’s state without re-rendering the component, but just its components

How do I change the useState without re-rendering it but just its components? Why I need is because I have some logic that changes the useState in Comp1. If I would re-render Comp1 I would have to recalculate its value. But if the change happens I still would like to re-render its components.

Edit: bigger code snippet.

function Comp1() {
  const [user, setUser] = useState({});

  firebase.auth().onAuthStateChanged(function (_user) {
    if (_user) {
      // User is signed in.
      setUser(_user);
    } else {
      setUser({ exists: false });
    }
  });

  return (
    <div>
      <UserProvider.Provider value={{user, setUser}}>
        <Comp2 />
        <Comp3 />
      </UserProvider.Provider>

    </div>
  );
}

function Comp2(props) {
  const { user, setUser } = useContext(UserProvider);
  return (
    <div>
      {user.exists}
    </div>
  )
}

function Comp3(props) {
  const { user, setUser } = useContext(UserProvider);
  return (
    <div>
      {user.exists}
    </div>
  )
}

//User Provider

import React from 'react';

const UserProvider = React.createContext();
export default UserProvider;

Advertisement

Answer

I took a shot at answering your question. Basically, you want to be able to calculate a value once and have it updated only when the content changes. You can do this with useEffect. The first parameter for useEffect is a function you want to happen on mount/update. It should return a function to run when your function is unmounted (if any). The second argument are the things that determine if useEffect gets ran. I put it to run when user changes value. Hopefully this is enough to get you started down the path of something. You can read more about useEffect in the docs.

function Comp2(props) {
  const { user, setUser } = useContext(UserProvider);
  const { state, setState } = useState({ value: '' });

  useEffect(() => {
    console.log(user);
    // perform expensive operation
    setValue({ value: 'My expensive operation is now stored' });
    return () => {
      // Do you have anything that you would put in componentWillUnmount()?
      // Put that here
    };
  }, [user]);

 console.log(state.value);

  return (
    <div>
      {user.exists}
    </div>
  )
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement