0

I want to explain it basically. This is not my code. It just for explain my issue. I know I can use the name parameter when I sending API requests but it's not my question.

const [deviceName, setDeviceName] = useState("iPad");

const changeDeviceName = (name) => {
     setDeviceName(name);
     sendNameToAPI(deviceName);
}

return (
    <div>
         <p>{deviceName}</p>
         <button  onClick={() => { changeDeviceName("iPhone"); }}>
    </div>
)

When setDeviceName works. In HTML deviceName change. It's OK but I want to use deviceName somewhere else in JS its coming "iPad". What can I do? Why? I research a lot I can't find to best practice. Someone say useEffect but If I have a lot of states it's mean a lot useEffect.

  • 1
    State is constant within a particular render of a component. Component can't see the updated state until it re-renders. You can use the `name` instead of `deviceName` if you want to call some function or do something with the latest value of state inside the same render of the component. Otherwise, you could use `useEffect` hook: `useEffect(() => { ... }, [deviceName])` – Yousaf Sep 30 '21 at 08:14

0 Answers0