React useState vs useEffect hooks

Zainab Omar
2 min readJul 30, 2021

Hooks are new feature introduced in React 16.8. It allows function components to use state and other React life cycle features without converting function component to class component. In this article I will talk about the difference between useState and useEffect hooks.

useState hook

useState is called inside function component to add local state to it. React will preserve this state between re-renders.

useState returns a pair: the current state value and function that lets you update it. setCount is similar to this.setState in a class component, except it doesn’t merge the old and new state together.

line 4 in code snippet above is similar to this code in class component

this.state = {count: 0}

if you want to declare multiple state variables in function component

function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}

in class component this is similar to:

this.state = {age: 42, 
fruit: 'banana',
todos: [{text: 'Learn Hooks'}]
}

useEffect Hook

useEffect hook is similar to componentDidMount, componentDidUpdate, and componentWillUnmount in class component.It tells React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates (data fetching is an example of side effects).

Rules of Hooks:

  1. Don’t call Hooks inside loops, conditions, or nested functions
  2. Don’t call Hooks from regular JavaScript functions.

Instead, always use Hooks at the top level of your React function, before any early returns.

for more details about React hooks refer to their documentation

--

--