what parts of a functional component gets run on a re-render?

Viewed 1105

I am used to class components in React, but am trying to learn React hooks. I know that in class components, there is render() method. This method is what is called whenever the class component gets re-rendered. However, for a functional component with state (react hooks), there is no such render() method. Is the entire function being run on every re-render? If so, doesn't the state get reset back to the default state value if every line of code of the function is run? Here is an example snippet — for instance, if this component gets re-rendered when I call setAnimal, doesn't the re-rendering make the animal be reset back to "dog"?

const SearchParams = () => {
  const [location, setLocation] = useState("Seattle, WA");
  const [animal, setAnimal] = useState("dog");

  return (
    <div className="search-params">
      <form>
        <label htmlFor="location">
          Location
          <input
            id="location"
            value={location}
            placeholder="Location"
            onChange={(e) => setLocation(e.target.value)}
          />
        </label>
        <label htmlFor="animal">
          Animal
          <select
            id="animal"
            value={animal}
            onChange={(e) => setAnimal(e.target.value)}
            onBlur={(e) => setAnimal(e.target.value)}
          >
            <option>All</option>
            {ANIMALS.map((animal) => (
              <option value={animal}>{animal}</option>
            ))}
          </select>
        </label>
        <button>Submit</button>
      </form>
    </div>
  );
};

1 Answers

The entire function is re-run. However, the useState() stores the state and does not get overridden. When you do useState("SOMETHING") the value you pass is the initial default value and only gets set once (aka on the first initialization of it).

React will remember its current value between re-renders, and provide the most recent one to our function. - Pulled directly from reactjs.org/docs/hooks-state.html

Based on what you asked I hope this answers it!

Related