DEV Community

Discussion on: State and Variable in React Hooks

Collapse
 
dance2die profile image
Sung M. Kim • Edited

When you put the somevariable outside of React's control, changing the value of somevariable would not trigger components depending on that value to re-render.

e.g.)

You can fork and try it yourself

Edit Doesn't re-render with global variable

let somevariable;

const Child = ({ somevariable }) => {
  useEffect(() => {
    console.log(`Child rendering with somevariable=>`, somevariable);
  });

  return <h1>{somevariable}</h1>;
};

async function fetchData() {
  return "some data";
}

const SomeComponent = () => {
  const [state, setState] = useState({});

  useEffect(() => {
    fetchData().then(data => setState({ data }));
  }, []);

  useEffect(() => {
    //update `somevariable` whenever the state changes
    somevariable = state.data;
  }, [state]);

  const clickMe = () => {
    console.log(somevariable, state);
    //do something to somevariable
  };

  return (
    <>
      <button onClick={clickMe}>Click Me </button>
      <Child somevariable={somevariable} />
    </>
  );
};

You can see that Child that depends on the change of somevariable does NOT render, as somevariable is not a state tracked by React.

The demo below doesn't render the Child component (with <h1>{somevariable}</h1> element)

does not rerender

Can you post a runnable code (possibly forking the sandbox) that causes the infinite loop?